PHP Tutorial PHP Advanced PHP References

PHP - Multi-dimensional Arrays



Multi-dimensional array can be viewed as arrays of arrays. In a multi-dimensional array, each element can also be an array. PHP allows you to define multi-dimensional arrays. The following syntax can be used to create a multi-dimensional array.

Syntax

//2-dimensional array
$MyArray = array(array(...), 
                 array(...),
                 ...,
                 array(...));               

Please note that, [] can also be used instead of array().

Two-Dimensional Arrays

The simplest form of the multi-dimensional array is a two-dimensional array. The below mention array shows a simple form of an associative multi-dimensional array. A multi-dimensional numeric array or mixed array can be created in the similar fashion.

$MyArray = array( 
    'John' => array(
           'age' => 25, 
           'city' => 'London'
           ),
    'Marry' => array(
           'age' => 23, 
           'city' => 'Paris'
           )
    );     

Values in the multi-dimensional array are accessed using multiple index. Consider the example below which demonstrates how to create, initialize and access elements of a multi-dimensional array.

<?php
//creating a 2-D array
$MyArray = array( 
    'John' => array(
           'age' => 25, 
           'city' => 'London',
           ),
    'Marry' => array(
           'age' => 23, 
           'city' => 'Paris',
           )
    );

//adding one more element in the array
$MyArray['Ramesh'] = array(
           'age' => 27, 
           'city' => 'Mumbai',
        );

//displaying the array
print_r($MyArray);

//accessing elements of the array
echo "John is ".$MyArray['John']['age'].
     " years old and lives in ".
     $MyArray['John']['city'].".";
?>

The output of the above code will be:

Array
(
    [John] => Array
        (
            [age] => 25
            [city] => London
        )

    [Marry] => Array
        (
            [age] => 23
            [city] => Paris
        )

    [Ramesh] => Array
        (
            [age] => 27
            [city] => Mumbai
        )

)
John is 25 years old and lives in London.

Complete PHP Array Reference

For a complete reference of all PHP Array functions, see the complete PHP Arrays Reference.