Welcome to S-Design
The home of your bespoke, professional, fast-loading, interactive, database-driven web presence.

PHP Arrays

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

echo $veg1;
echo $veg2;
echo $veg3;
echo $veg4;
echo $veg5;
and compare it with this example: <?PHP

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.

There are a few ways in which you can create an array in PHP.

Example 1: <?PHP
This 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.
In newer versions of PHP, you can also start this kind of array using the same method that JavaScript uses... without the array() part: $veg=["peas","carrots"];

Example 2: <?PHP
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";

Example 3: <?PHP
This 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.

Example 4: <?PHP
This 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.