Navigation
Poll
Would you be an active poster if Ron's Guide had a message board?


Total Votes: 62
Comments: 18 — View
Past pollsPoll idea?
Rate Ron's Guide
Rate our resource at Bigwebmaster.com
Utilizing Arrays
Arrays are one of the most useful tools in any programming language, this tutorial will introduce you to arrays and associative arrays.

You can also give array keys names, instead of numbers. These are called associative arrays. Here is an example of an associative array:



<?php

$personal_info 
= array(
                 
'name' => 'Ron',
                 
'site' => 'ronsguide.com',
                 
'mail' => 'ron@ronsguide.com'
);

?>

The above creates a variable that holds an associative array with some information about me. Notice the differences in how associative arrays are created compared to normal arrays. You still separate each item by commas, but in associative arrays you specify the key name, followed by the value:

key => value

You can add items to exisiting associative arrays too,
here's an example of how this is done:

<?php

$personal_info
['age'] = 21;

?>

That will add an array item with the key 'age' and the value '16' to the array. The array now looks like this:

Array
(
    [name] => Ron
    [site] => ronsguide.com
    [mail] => ron@ronsguide.com
    [age] => 21
)

pretty easy huh? It's easy to access the information in an associative array too...

You access associative arrays much like you do normal arrays, the only difference is with the keys, instead of number you use the key names. For example:

<?php

echo 'Hello, my name is '.$personal_info['name'].'.
Visit my website: '
.$personal_info['site'].'.
You can contact me at '
.$personal_info['mail'].'.';

?>

The above code will have the following output:
Hello, my name is Ron. Visit my website: ronsguide.com. You can contact me at ron@ronsguide.com.


Hopefully this tutorial helped you to understand arrays and associative arrays a little better. If you have any questions feel free to ask using the "Discuss this tutorial" link in the right column, under "Tutorial Options." Smile

« Previous [ 1 2 ] Next »
Discuss Tutorial: Utilizing Arrays 5 Comments
Comment by Ron on Aug 15, 2004, 8:26 am
Please post questions or comments about this tutorial below. Smile
Comment by Zaki on Jan 16, 2005, 2:39 am
Grin Nice tutorial
Comment by poo on May 14, 2005, 7:46 pm
finally something worth reading Smile
Comment by Liveman on Jan 6, 2006, 10:16 pm
I have only one question, why do you call the $myFav variable, why not just echo $fruits[1] ??
Comment by Ron on Feb 4, 2006, 5:11 am
No reason really, both ways give you the same effect. Tongue

« Previous [ 1 ] Next »
Post a comment
Sorry, you must be a registered member to post comments.

If you would like to register, you can do so here.
If you already have an account, please login.