PHP Arrays

PHP arrays allow you to store groups of related data in one variable (as opposed to storing them in separate variables). Storing data like this in an array has many benefits.

For example, if you have a lot of data, you could populate the array programmatically. You could also output the contents programatically — all you need to know if the name of the array.

There are 3 different types of PHP arrays:

Numeric Arrays

Numeric arrays use a number as the "key". The key is the unique identifier, or ID, of each item within the array. We can use this ID later when working with the contents within the array - we don't need to know the item's value, just the ID.

Note that numbering starts at zero.

Creating Numeric Arrays

You can choose between the following options when creating an array. Both of these options have the same result.

Displaying the Array Contents

You can work with each value in an array by referring to its key. For example, to select the 2nd value in an array, we would do this: $arrayName[1]. Just a reminder that numbering starts at zero, so the 2nd item actually uses the number one as it's key.

Example:

The above code results in:

Strawberries

Associative Arrays

Associative arrays are similar to numeric arrays but, instead of using a number for the key, we use a value. We then assign another value to the key - you could think of it as two values for the price of one!

Creating Associative Arrays

As with creating numeric arrays, there are two options for creating associative arrays in PHP (although in both cases, we have to create the key manually).

Displaying the Array Contents

You can display the contents of associative arrays just as you would with numeric arrays - by referring to it's key.

The above code results in the following:

Artichoke: 105 kilojoules

Multidimensional Arrays

Multidimensional arrays allow you to put an array inside another array. In other words, the contents of the array is another array. You can do this as many times as you wish - you could have an array inside another array, which is inside another array, etc

The following diagram demonstrates this. We have an array called "Food", which contains 3 arrays (called "Fruit", "Vegetables", "Grains"). Each of these arrays contain their own arrays (one for each food within that group).

Food
Fruit
Apples
Bananas
Oranges
Vegetables
Carrots
Potatoes
Grains
Oatbran

Creating a Multidimensional Array

We can create the above array using the following code: