php
  1. php-multidimensional-array

Php Multidimensional Array

A multidimensional array is an array containing one or more arrays. In PHP, a multidimensional array is simply an array whose elements can also be arrays.

Syntax

The syntax for creating a multidimensional array in PHP is as follows:

$arrayName = array(
  array(value1, value2, value3),
  array(value4, value5, value6),
  array(value7, value8, value9)
);

Example

The following example shows how to create a multidimensional array:

$cars = array (
    array("Volvo",22,18),
    array("BMW",15,13),
    array("Saab",5,2),
    array("Land Rover",17,15)
);

Output

The above example will create a multidimensional array named $cars. The output of the print_r() function applied on $cars array will be:

Array
(
    [0] => Array
        (
            [0] => Volvo
            [1] => 22
            [2] => 18
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
            [2] => 13
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
            [2] => 2
        )

    [3] => Array
        (
            [0] => Land Rover
            [1] => 17
            [2] => 15
        )

)

Explanation

In PHP, multidimensional arrays are simply nested arrays. Each element of a multidimensional array can be an array itself. From the example above, the $cars array contains four arrays, each with three elements. The first array represents a Volvo car with 22 miles per gallon in the city and 18 miles per gallon on the highway. Similarly, the other arrays represent different types of car with their fuel consumption details.

Use

Multidimensional arrays are used when you want to store data in a structure that is more complex than a simple linear array. They are very useful for representing data that is naturally hierarchical, such as organizational charts, family trees, or geographical data.

Important Points

  • A multidimensional array is an array of arrays.
  • Each element of a multidimensional array can be an array itself.
  • The number of dimensions in an array is limited only by the amount of memory available.
  • You can access a specific element in a multidimensional array by using its key or index.

Summary

In PHP, a multidimensional array is simply an array containing one or more arrays. They are useful for storing data in a hierarchical structure. You can access a specific element in a multidimensional array by using its key or index.

Published on: