dan forys

blog

Learning PHP - Part 3: array basics

Posted on 2009-10-26 - Comments

In part 2, you were introduced to the concept of variables and the string, integer and floating point types. In part 3 we’ll go through a more advanced type; the array.

What is an array?

An array is a list of values. Each value has a unique name which is called its key.

Imagine you wanted to store a list of colours: Red, Blue and Yellow. You can store this in an array as follows:

$colours = array('Red', 'Blue', 'Yellow');

Here, you assigned the array of values to a variable called “$colours”. Each item in this array (called an element) is a string (remember strings are enclosed by single or double quotes). Note that each item in the array is separated by a comma, and the whole list is enclosed in brackets.

Outputting an array

This is all very nice, but how do we get the items out of the array? You can’t simply echo out an entire array. This is where PHP has some very powerful functions. One of the most common, is the foreach:

foreach ($colours as $item) {
  echo $item . '<br />';
}

This is the first example of a PHP loop. Foreach goes through each item in an array and lets you perform operations on it. Here, we are telling it to operate on the $colours array we defined above. In turn, each item in the array is assigned to a second variable called $item. The two curly braces ‘{‘ and ‘}’ enclose a set of instructions to run on each element; in this case echoing out the item followed by an HTML break. This gives:

Red
Blue
Yellow

Note that foreach always operates on the elements in the same order that they were put into the array.

Another, slightly more complicated example. This time, we’ll use an array of integers:

$numberArray = array(3,4,5);
$total = 0;
foreach ($numberArray as $number) {
  $total = $total + $number; // this adds $number to the current value of $total
}
echo 'The total is ' . $total;

In this example, after creating the array, we have also created a variable called $total, setting its value to 0. Using foreach, we then loop through each element of the $numberArray and add it to the $total. Finally, we echo out the total, giving this result:

The total is 12

Mixed arrays

Arrays needn’t be just lists of a single type; you can mix and match as you like:

$mixedArray = array('Fred', 23, "Cheesy nibbles", 19.6);

Each element in the array has its own type, just as when you assign values to variables. This becomes very useful when we deal with more advanced topics.

Array keys

At the start, we mentioned that each item in an array has a key, as well as a value:

If you don’t explicitly supply a key, PHP will automatically number your elements, starting from 0

Remember the colours array from the start of this post? This means that when we created the array, Red had the key 0, Blue had a key of 1 and Yellow was 2. The keys give you a way of referring to specific elements in the array. One way of doing this is with square brackets:

$colours = array('Red', 'Blue', 'Yellow');
echo $colours[1]; // outputs 'Blue' - numbering starts from 0!
echo $colours[2]; // outputs 'Yellow'
echo $colours[3]; // not defined, may show an error depending on configuration

You can use the same syntax to define an element with a specific key:

$colours[7] = 'Purple';

Now the array has a new item ‘Purple’ with a key of 7. Now there are four items in the array: Red (0), Blue (1), Yellow (2), Purple (7). Note that the keys don’t need to be consecutive.

You can also specify the array keys when you initially create the array, using PHPs ‘=>’ notation:

$colours = array(0=>'Red', 7=>'Purple', 1=>'Blue', 2=>'Yellow');
foreach ($colours as $item) {
  echo $item . '<br />';
}

Remember that foreach loops through the items in the order they were inserted; regardless of its key. This means the above code outputs:

Red
Purple
Blue
Yellow

You can also use the keys in a foreach loop:

$colours = array(0=>'Red', 7=>'Purple', 1=>'Blue', 2=>'Yellow');
foreach ($colours as $key => $item) {
  echo 'Key ' . $key . ' has value ' . $item . '<br />';
}

Now, each time a $item is fetched from $colours, its corresponding key is assigned to the variable $key. It uses the same ‘=>’ notation as above. This results in:

Key 0 has value Red
Key 7 has value Purple
Key 1 has value Blue
Key 2 has value Yellow

Associative arrays

Just as array items can be different types, so can their keys. This is an immensely useful feature of PHP that you will refer to again and again. Arrays with non-numeric keys are called associative arrays.

You define an associative array in exactly the same way as any other array. Here, we’ll define an array of details about a person:

$person = array('name'=>'Fred', 'age'=>25, 'dislikes'=>'Mushrooms);
echo $person['age']; // outputs 25

You can use square brackets to assign associative values as well. This example is equivalent to the previous:

$person = array();
$person['name'] = 'Fred';
$person['age'] = 25;
$person['dislikes'] = 'Mushrooms';

To conclude

Arrays are one of the most useful types in PHP; so feel free to play around with the examples above until you feel confident with them.

Now you’ve been through the basics of variables and arrays, we can go on to build your first dynamic web page in part 4.