Different types of PHP Arrays

Different types of PHP Arrays

There are three types of php arrays:

  1. Indexed.
  2. Associative.
  3. Multi-Dimensional.

Indexed Arrays

  • This is an array that has a numeric key. Like in JavaScript, the arrays are zero-based indexing, that is, they start counting from zero.
<?php
 $cities = array('Nairobi','Mombasa','Kisumu');
?>
echo $cities[2];

The output of the above array is Kisumu.

Here is a break-down of zero-based indexing:

<?php
$cities[0] = "Nairobi"; 
$cities[1] = "Mombasa"; 
$cities[2] = "Kisumu"; 
?>

Associative Arrays

  • This is an array where each key has its own specific value.

Example:

<?php
$cities = array('Nairobi' => 40,'Mombasa' => 60,'Kisumu'=>10);
?>
echo $cities['Nairobi'];

The above will give an output of 40 as the key 'Nairobi' is associated with that value. A break-down of the above will be as follows:

<?php
$cities['Nairobi'] = 40; 
$cities['Mombasa'] = 60; 
$cities['Kisumu'] = 10; 
?>

Multi-dimensional Arrays

  • This is an array in which each element can also be an array and each element in the sub-array can be an array or further contain an array within itself. Example:
<?php
$cars = array(
             array('Honda','Toyota','Mazda'),
             array('BMW','Volkswagen','Mercedes),
             array('Probox','Vitz')
             );
?>
echo $cars[1][2];

The output of the above example will be Mercedes. Explanation

echo $cars[1]  //this will first index the multiple arrays thus array('BMW','Volkswagen','Mercedes) falls in that category

The second bit is as follows

echo $cars[2] //picks the third variable from the array picked above

Another example of a multi-dimensional:

<?php
// Define a multidimensional array
$superHeroes = array(
    array(
        "name" => "Bruce Wayne",
        "city" => "Gotham",
    ),
    array(
        "name" => "Arthur Curry",
        "city" => "Asgard",
    ),
    array(
        "name" => "Barry Allen",
        "city" => "Central City",
    )
);
// Access nested value
echo "The Flash's hometown is : " . $superHeroes[2]["city"];
?>

On the above example - we have combined both the Indexed and associative array, thus the output will be: The Flash's hometown is: Central City. Explanation:

echo $superHeroes[2] //picks the array to get our values from.
echo $superHeroes["city"] //gives the value of the key associated with city in the array.

This is my very first article and I hope it has helped you in understanding arrays in php. Thank you very much for reading it.