Easy Tutorial
❮ Filter Validate Email Func String Lcfirst ❯

PHP Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

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

A value in an array can be another array, and a value in that array can also be an array. In this way, we can create two-dimensional or three-dimensional arrays.

Syntax for a two-dimensional array:

array (
    array (elements...),
    array (elements...),
    ...
)

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

Example

<?php
// Two-dimensional array:
$cars = array
(
    array("Volvo",100,96),
    array("BMW",60,59),
    array("Toyota",110,100)
);
?>

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

Example

<?php
$sites = array
(
    "tutorialpro" => array
    (
        "tutorialpro.org",
        "http://www.tutorialpro.org"
    ),
    "google" => array
    (
        "Google Search",
        "http://www.google.com"
    ),
    "taobao" => array
    (
        "Taobao",
        "http://www.taobao.com"
    )
);
print("<pre>"); // Format the array output
print_r($sites);
print("</pre>");
?>

The above array will output as follows:

Let's try to display a specific value from the above array:

echo $sites['tutorialpro'][0] . ' address is: ' . $sites['tutorialpro'][1];

The above code will output:


Three-dimensional Array

A three-dimensional array is a two-dimensional array with an additional layer of arrays, formatted as follows:

array (
    array (
        array (elements...),
        array (elements...),
        ...
    ),
    array (
        array (elements...),
        array (elements...),
        ...
    ),
    ...
)

Example

<?php
// Create a three-dimensional array
$myarray = array(
    array(
        array(1, 2),
        array(3, 4),
    ),
    array(
        array(5, 6),
        array(7, 8),
    ),
);

// Output array information
print_r($myarray);
?>

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
                )

        )

)
❮ Filter Validate Email Func String Lcfirst ❯