PHP Arrays

May 15th, 2012

An array is simply a collection and an efficient method of manipulating data.
Arrays can hold multiple values in one variable.

You create an array using the array() function or the array operator [].
There are three main types of arrays used in PHP.

  • Numerically Indexed Arrays
  • Associative Arrays
  • Multidimesional Arrays

Which type you use, depends on the data you are working with / outputting.

Numerically Indexed Arrays

<?

// An Indexed array example

$test = array('Orange', 'Apple', 'Kumkwat', 'Lychee');
print_r($test);

/*
The above will output the following:
Array ( [0] => Orange [1] => Apple [2] => Kumkwat [3] => Lychee )
*/

?>

The above example is known as an numerically indexed array because the index position is used for the key (0, 1, 2, 3). PHP adds the key automatically.

Associative Arrays

An associative array is different because you can use names for the keys.
Here we are using “name”, “colour” and “type” as the keys.

<?

// An Associative array example

$test = array(
        "name" => "Apple",
        "colour" => "Green",
        "type" => "Gala"
        );

print_r($test);

/*
The above will output the following:
Array ( [name] => Apple [colour] => Green [type] => Gala ) 
*/

?>

Multidimensional Arrays

A Multidimensional array is basically an array within an array.
Each element contains as associative array.

The above example is known as an indexed array because the index position is used for the key (0, 1, 2, 3).
An associative array is different because you can use names for the keys.

<?

// An Associative array example

$test = array(
          array(
            "name" => "Apple",
            "colour" => "Green",
            "type" => "Gala"
          ),
          array(
            "name" => "Melon",
            "colour" => "Yellow",
            "type" => "Honeydew"
          ),
          array(
            "name" => "Banana",
            "colour" => "Yellow",
            "type" => "Manzano"
          )
        );

print_r($test);

/*
The above will output the following:

Array
(
    [0] => Array
        (
            [name] => Apple
            [colour] => Green
            [type] => Gala
        )

    [1] => Array
        (
            [name] => Melon
            [colour] => Yellow
            [type] => Honeydew
        )

    [2] => Array
        (
            [name] => Banana
            [colour] => Yellow
            [type] => Manzano
        )

)
*/

?>

You can also access a single element of the array by using its index:

$test[0][‘name’] = ‘Apple’;
$test[1][‘name’] = ‘Melon’;

Looping through Arrays to Output Data

Looping through a numerically indexed or associative array is a case of using a foreach loop:

<?

// Looping through the elements of an associative array

$test = array('Orange', 'Apple', 'Kumkwat', 'Lychee');
print_r($test);

foreach($test as $row) {
    echo $row . "
";
}

/*
The above will output the following:

Orange
Apple
Kumkwat
Lychee

*/

?>