PHP Arrays

Variables can only store a single value, so adding many more would be time consuming. That’s where arrays come in, since arrays can store multiple values. For example, if you wanted to list your favourite movies you could make each variable or use arrays.

Syntax

$variable_name = array ('value1', 'value2');

Here we get a list of movies

$movies = array ('Avatar','The Karate Kid','Transformers','Rambo');

Instead of doing $movies = ‘Avatar’ we use the array keyword open brackets and then single or double quotation marks around our movies, separating each with a comma. However you cannot print this out. Each movie is given an ID. At the bottom of $movies, put:

print_r ($movies);

View it in the browser and you should get something like this:

Array ( [0] => Avatar [1] => The Karate Kid [2] => Transformers [3] => Rambo )

Here you have the word array, then open brackets and then your movie ID. So Avatar = 0 Karate Kid = 1 and so on. Remember, the first value in the array is a 0, not 1. Now to echo  type echo $movies [0];

echo $movies[1];

This will output The Karate Kid.

Key Name

In the above example, the array is referenced by its number such as $movies[1]. You can change this and call an array by its key name.

Syntax

$movies = array ('keyname' => 'value', )

Commas separate the values like before.

Example

$movies = array ('ava' => 'Avatar', 'tkd' => 'The Karate Kid', 'Tran' => 'Tranformers', 'ram' => 'Rambo');

Now to output the values, instead of using the number you use the key name.

echo $movies[tkd];

This will output The Karate Kid.

Looping through arrays

You can loop through arrays using a Foreach statement.

Syntax

foreach ($arrayname as $localvariable)
{
..code to execute
}

Example

foreach ($movies as $values)
{
echo '<br/>'.$values.'<br/>';
}

This loops through the array movies.

Sorting Arrays

The table below shows the functions which sort arrays out.

Functions Description
implode Converts array to string
explode Converts string to array
sort Sorts array by value (ascending) if you specify a key name it is removed (goes back to numbers)
asort Sorts by array value but keeps key (ascending)
ksort Sorts array by key (ascending)
rsort Same as sort but descending
arsort Same as asort but descending
krsort Same as ksort but descending
count Shows the amount of elements in an array

Syntax

function($arrayname);

Example

sort($movies); foreach ($movies as $values) { echo '<br/>'.$values.'<br/>'; }

Here we use a Foreach statement to print out the arrays. They will be in alphabetical order, and the arrays will have the key names removed. If you write

print_r ($movies);

below the Foreach statement, you will see that the key names have been replaced with numbers.If you do not want this to happen, use asort or arsort.

Output

Avatar
Rambo
The Karate Kid
Tranformers