If you can think of a variable as a box to put data in it then an array is a box of boxes!  Each box gets a label but they are all collected into a bigger box for ease of handling.  If you currently have a mental picture of cardboard boxes being carried by a delivery person you are spot on.

Indexed arrays

To access data in an array you need to know the array name and the box inside it which you want.  Open your PHP template and save it as phparrays.php.  Paste this code into the usual place:


The square brackets and numbers identify which element inside the array you want to use.  Here data is going into the array but you use the same method to get it out.

PHP is quite sloppy in how it works so the above code both creates the array ($george) and puts the data into it.  There is now one array with three items of data in it.  In computing you number things from 0 upwards not from 1 upwards.

You can try that code on the server to test it but as there is no output nothing will be seen.  All that has happened is that the server now knows about the array called $george.

You can put anything in an array but they are normally used to group related things together (all of the above data is about one person).

Displaying array data

You already used print_r to display the data inside $_POST.  It is also time to use another HTML element called pre which presents text complete with the original spaces, tabs and line returns.

Add this code under the existing three lines and then save, upload and try the page:

echo "<pre>";
echo "</pre>";

Your should see this:

A PHP array displayed by print_r

You could also echo just one of the items at a time by using the index number of the element in square brackets.  Or you can mix text and data from the array in a sentence.  Add this under the existing six lines of code:

echo "<p>This person is called {$george[0]} {$george[1]} and played the {$george[2]}.</p>";

This might seem fairly basic and pointless but you are now using PHP to create page content from stored data.  Once you know how to get that data from a database you can create any Web site you want.  First a bit more PHP.

Associative arrays

Although PHP is quite a sloppy programming language it was written by users and so is quite friendly.  People sometimes struggle with remembering numbers.  You might not be able to remember whether you put personal names first or family names first in the array.  Is $george[0] the personal or the family name?

PHP provides a much more human way of storing data in an array.  Under the existing seven lines of code paste this:

echo "<pre>";
echo "</pre>";

Save, upload and try.  You now have two arrays with two ways of identifying each part.  Either is fine.