Array Variables

Arrays are a special type of variables. A regular variables allows you to store only one set of data, but an array allows you to store multiply number of data.

Arrays are similar to storing data in a list.

E.g. if you want to store several colours as normal variables it’ll look something like the below:

[php]
$colour1 = "blue";
$colour2 = "red";
$colour3 = "yellow";
[/php]

It will get a bit messy if the list grown too big. It will also become extremely difficult for your script to find a particular one. The best solution is to use an array.

Declaring an array
Below is a simple way of declaring a basic array.

[php]
$colours = array("red", "blue", "yellow");
[/php]

Printing an array
We normally print variables to screen using echo, but we need to use print_r() for array like below:
[php]
print_r($colours);
[/php]
That will output:

Array = (
[0] = “blue”,
[1] = “red”,
[2] = “yellow”
)

You can print each of the individual values in the array. You can use echo for this.
[php]
echo $colours[1];
[/php]
That will output:

blue

Key & Value
There are two important terms used with arrays. These are “key” and “value“.

The association between these two terms is very simple. A value is always associated with a key and a key is always assigned a value (the value can be blank).

Lets look at how we identify the key and value in an array. Below is an example of an array if outputted to the screen.

Array = (
[0] = “blue”,
[1] = “red”,
[2] = “yellow”
)

The keys in the example are 0,1 & 2. The values are blue, red & yellow. See how they are associated with each other?

Array Types
There are three types of arrays. We will go through each one by one.