Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Multidimensional Arrays

PHP Multidimensional Arrays


A multidimensional array is an array that contains one or more arrays.

In a multidimensional array, each element in the main array can also be an array, and each element in a sub-array can also be an array.

The value in one array can be another array, and the value in that other array can also be an array; in this way, we can create two-dimensional or three-dimensional arrays.

Two-dimensional array syntax format:

array (

    array (elements...),

    array (elements...),

    ...

)

The elements of the above array are automatically assigned keys starting from 0:

Example

Run Example »


In the example below, we create a two-dimensional array with specified keys (associative array):

Example

array ( "Runoob Tutorial" , "http://www.runoob.com" ), "google" =>array ( "Google Search" , "http://www.google.com" ), "taobao" =>array ( "Taobao" , "http://www.taobao.com" ) ); print( "
"



); 



// Format the output array

 



print_r



(



$sites



);      

 print(



"
" ); ?>

The above array will output as follows:

Let's try to display a certain value in the array above:

echo $sites['runoob'][0] . '地址为:' . $sites['runoob'][1];

The code above will output:


Three-dimensional array

A three-dimensional array nests one more level of arrays on top of a two-dimensional array, with the format as follows:

array (

    array (

        array (elements...),

        array (elements...),

        ...

    ),

    array (

        array (elements...),

        array (elements...),

        ...

    ),

    ...

)

Example

The above array will output as follows:

Array

(

    [0] => Array

        (

            [0] => Array

                (

                    [0] => 1

                    [1] => 2

                )



            [1] => Array

                (

                    [0] => 3

                    [1] => 4

                )



        )



    [1] => Array

        (

            [0] => Array

                (

                    [0] => 5

                    [1] => 6

                )



            [1] => Array

                (

                    [0] => 7

                    [1] => 8

                )



        )



)