You should already know what an array is.
The simplest way to access arrays in PHP
The array has one name but inside it are values which you can point to using a number. In the code the number is put inside square brackets:
$names[0]="George";
$names[1]="John";
$names[2]="Paul";
$names[3]="Ringo";
The array has four items in it now but more can be added later. The items (or elements) in the array can be identified by their key. The key is the bit in square brackets. Each element in an array is made up of a key and a value.
You can use the array values just like any other variables:
$numbers[0]=2;
$numbers[1]=8;
$total=$numbers[0]+$numbers[1];
Note that the same array could hold numbers or text (strings). The last example used numbers and no quotes. In the first example quotes were used as the data was text.
Arrays are useful for holding lots of data of similar types.
Associative arrays
Rather than using numbers as keys you can associate the values with the keys in a more human way:
$names["guitar1"]="George";
$names["guitar2"]="John";
$names["bass"]="Paul";
$names["drums"]="Ringo";
This is known as an associative array. These will become a lot more useful when you use MySQL.
Printing a whole array
Although you would rarely want to do it for users you can print the whole of an array. This is very useful to show what is in it for troubleshooting or planning how to handle the data. PRINT_R does the same as ECH but with arrays:
echo "<pre>";
print_r($names);
echo "</pre>";
The PRE tags just force the browser to display the array content as PRINT_R displays it rather than ignoring line breaks and tags as it otherwise would.
Practise
Create a new PHP page complete with the basic HTML HEAD etc.. Call it arraysandloops.php. Paste in the lines from the top of this page which set the array values. After that paste the three lines from the PRINT_R example. Upload the page and try it. It should output all of the names in the array with the index key used to access them (0 to 4) with a => symbol to separate key from the value. That is supposed to look like an arrow and does not mean "equal to or greater than".
Now replace the code from the first example on this page with the code from the third. This is the chunk where keys are used (e.g. guitar1 etc.). Note the difference in the PRIN_R results.



