We learnt in the previous PHP Variables section, that variables are a kind of temporary storage area, where $variable="something". Arrays are a collection of variables, all stored together under one variable name.
Let's take a look at this example:
<?PHP
and compare it with this example:
$veg1="peas";
$veg2="carrots";
$veg3="parsnips";
$veg4="potatoes";
$veg5="broccoli";
echo $veg1;
echo $veg2;
echo $veg3;
echo $veg4;
echo $veg5;
?>
<?PHP
$veg=array("peas","carrots","parsnips","potatoes","broccoli");
for($i=0;$<count($veg);$i++){
echo $veg[$i];
}
?>
In the first example, we use 5 different variables to store 5 different bits of information, and we then print out each bit, by echoing the value of each variable.
This is great if you know how many bits you have, and you know their name.
In the second example, we use one variable which has been set as an array. We then use a loop to go through that array and print out each one.
We'll cover PHP Loops in greater detail later, but as you can see we don't need to print out each variable individually, and we don't need to know how many there are.
Arrays then, are great if you need to group lots of related information together, so you can either sort them (alphabetically, for example), or you need to be able to go through them in a loop.
<?PHP
$veg=array("peas","carrots","parsnips","potatoes","broccoli");
?>
This simply sets your variable called $veg to be an array, and includes it's values. This is great if you know the values at the time of setting the array, and you know how many there are.
<?PHP
$veg=array();
$veg[0]="peas";
$veg[1]="carrots";
$veg[2]="parsnips";
$veg[3]="potatoes";
$veg[4]="broccoli";
?>
This simply sets your variable called $veg to be an array, but includes no values. Then, as you work your way through your PHP script, you can assign a value at any time with $veg[0]="peas";
<?PHP
$myveg="peas,carrots,parsnips,potatoes,broccoli";
$veg=explode(",",$myveg);
?>
This takes a string variable called $myveg and explodes in into parts using the the comma as a separator, and places those parts in an array called $veg.