PHP Multidimensional Arrays

In PHP, a multidimensional array is an array that contains one or more arrays as its elements. These arrays can be either indexed arrays or associative arrays. Multidimensional arrays provide a way to represent and work with complex data structures, such as matrices, tables, and hierarchical data.

Here’s an example of a multidimensional array:

$students = array(
    array("John", 20, "A"),
    array("Jane", 19, "B"),
    array("Mike", 21, "A")

In this example, we have created a multidimensional array called $students. It consists of three elements, where each element represents a student’s information as an indexed array. Each student’s information array contains three elements: name, age, and grade.

You can access individual elements in a multidimensional array by specifying both the outer and inner indexes.

For example:

echo $students[0][0];  // Output: John
echo $students[1][1];  // Output: 19
echo $students[2][2];  // Output: A

You can also use associative arrays as elements of a multidimensional array.

Here’s an example:

$products = array(
        "name" => "Apple",
        "price" => 0.99
        "name" => "Banana",
        "price" => 0.59
        "name" => "Orange",
        "price" => 0.79

In this case, each element of the $products array is an associative array representing a product’s information. Each product’s information array contains two elements: name and price.

You can access elements in a multidimensional associative array using both the outer and inner keys.

For example:

echo $products[0]["name"];   // Output: Apple
echo $products[1]["price"];  // Output: 0.59
echo $products[2]["name"];   // Output: Orange

Multidimensional arrays can have any number of dimensions, allowing you to represent even more complex data structures. You can use loops, such as nested for loops or foreach loops, to iterate through and manipulate the elements of a multidimensional array.

Multidimensional arrays are commonly used when you need to organize and work with structured data that has multiple layers of information. They provide a powerful way to store, access, and manipulate data in a hierarchical manner.

Reference documents read more.