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.

Arrays are very useful for storing multiple pieces of information in a single variable. PHP has many built in functions that allow you to store, manage and manipulate arrays in various ways. What exactly is an array, anyway?

An array is basically an arrangement of data. You can use them to store all sorts of information, for instance, I use arrays for this website to store the data for the poll you see in the left column. I also use them to store the information of the tutorials on this site... titles, descriptions, views, etc.

To create an array, all you need to do is call upon the array() function.
An example array is shown below.

<?php

$fruits 
= array('apples','bananas','oranges','grapes');

?>

The code above creates an array with the values between the parenthesis, each piece separated by commas becomes a new item in the array. You can also add items to an already existing array, here is an example how:

<?php

$fruits
[] = 'pears';

?>

PHP will automatically add a new array item containing 'pears' to the end of the array. So now the array will look like this:

Array
(
    [0] => apples
    [1] => bananas
    [2] => oranges
    [3] => grapes
    [4] => pears
)

Each item in the array has what is called a 'key'. As you can see in the array above the keys are numbers, starting from 0 the keys increment by 1. For example, the key for the value 'apple' is 0, the key for 'banana' is 1, and so on.

The keys of the array items are important when you want to grab the values of the items in the array. To do this, you use this syntax:
$value = $array_name[key_number];

Here is an example:

<?php

$fruits 
= array('apples','bananas','oranges','grapes');
$myFav $fruits[0];
echo 
$myFav.' are my favorite fruit.';

?>

The above code will write 'apples are my favorite fruit.' onto the webpage.
We're not done yet, go to the next page to learn more.

« 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.