1. php
  2. /references
  3. /multidimensional-array

PHP Multidimensional Arrays

A PHP multidimensional array is an array that contains one or more arrays, which can be accessed using multiple indices.

Usage

Here's an example of a multidimensional array:

$students = [
    ['name' => 'John', 'age' => 30, 'gender' => 'male'],
    ['name' => 'Jane', 'age' => 25, 'gender' => 'female'],
    ['name' => 'Bob', 'age' => 28, 'gender' => 'male']
];

Looping through an multidimensional array

To loop through a multidimensional array, you can use nested foreach loops. Here's an example of how to loop through the $students array and print out each student's name and age:

foreach ($students as $student) {
    foreach ($student as $key => $value) {
        if ($key == 'name' || $key == 'age') {
            echo "$key: $value\n";
        }
    }
    echo "\n";
}

This will output:

name: John
age: 30

name: Jane
age: 25

name: Bob
age: 28

You can also use a for loop with the count function to loop through the outer array, and a foreach loop to loop through the inner arrays. Like so:

for ($i = 0; $i < count($students); $i++) {
    foreach ($students[$i] as $key => $value) {
        if ($key == 'name' || $key == 'age') {
            echo "$key: $value\n";
        }
    }
    echo "\n";
}

This will output the same as the first method.

See also:

PHP Indexed Array

PHP Associative Array