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:
and compare it with this example:
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.
There are a few ways in which you can create an array in PHP.
<?PHPThis simply sets your variable called $veg to be an array, and includes its values. This is great if you know the values at the time of setting the array, and you know how many there are.
<?PHPThis 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="peas";
<?PHPThis simply sets your variable called $veg to be an array, but includes no values. Then at any place in your script you can simpy push a new item into the $veg array. You don't need to know how many items are already in the array, as array_push() simply adds new items to the bottom.
<?PHPThis takes a string variable called $myveg and explodes it into parts using the the comma as a separator, and places those parts in an array called $veg.
$veg will now look exactly as it does in Examples 1, 2 & 3 above.
We don't need to tell $veg to be an array first, as the explode function does this for us.