Creating an Array

An array is like a column in a spreadsheet. The array name is like a column heading, with the array having a list of values. For example, take a list of colours (red, green, blue, etc.). This would be defined in an array as follows:

$colour[0] = 'Red';
$colour[1] = 'Blue';
$colour[2] = 'Green';

Note that the index value used to reference the positions in the list starts at 0 in PHP. Exactly the same can be done using this:

$colour = array(0 => 'Red', 1 => 'Blue', 2 => 'Green');

You can add elements to the end of an array like this using brackets without a number in it. For example,

$colour[ ] = 'White';

will add this to the end of the array at number 3. The number inside the bracket is known as the key. You can use strings as keys if you wish.

$name['first'] = 'John';
$name['middle'] = 'Albert';
$name['last'] = 'Smith';

Next article: Date and Time

Using Arrays

To access an array element, just use the key you used to create the element in the first place.

$chosen = $colour[2];
$fullname = $name['first'] . $name['middle'] . $name['last'];

A common thing to want is to read through a numeric array to find something. To do this, loop through the array until there are no more elements. Use the count function to find out how many elements there are. For example:

$max = count($arrayname);
for ($i=0; $i <= $max; $i++) {
    $element = $arrayname[$i];
... do want you want with $element now

Next article: Date and Time


The previous article tells you how to use loops and how to make decisions in PHP.


The next screen gives you a tutorial on how to use the date function in PHP.
This tutorial tells you how to retrieve dates and times, including the current date and time.

External Links


  • Create an array using the key values and a value for each element
  • Add to the end of a numeric array using [ ]
  • Retrieve an element in an array using its key
  • Use count to find out how many elements are in an array