How to loop through a multidimensional array using foreach in PHP

When you have a multidimensional array, you can use the foreach construct to loop through that array.

You need to use two foreach statements as shown in the following code:

<?php
// A multidimensional array of user data
$users = [
    [
        "id" => 1,
        "name" => "Nathan",
        "age" => 29,
    ],
    [
        "id" => 2,
        "name" => "Susan",
        "age" => 32,
    ],
    [
        "id" => 3,
        "name" => "Jane",
        "age" => 23,
    ],
];

foreach ($users as $index => $user) {
    // print the array index
    print "Array index : {$index}";
    print PHP_EOL; // breaking space
    foreach ($user as $key => $value) {
        print "{$key} : {$value}";  // print key and value
        print PHP_EOL;
    }
}

The above code will give the following output:

Array index : 0
id : 1
name : Nathan
age : 29
Array index : 1
id : 2
name : Susan
age : 32
Array index : 2
id : 3
name : Jane
age : 23

The first foreach statement will loop through the main array, while the second statement loops through each child array.

You can also use the same code when looping through an associative multidimensional array as shown below:

<?php
// Create a multidimensional associative array
$members = [
    "Front-end developer" => [
        "name" => "Nathan",
        "age" => 29,
    ],
    "Back-end developer" => [
        "name" => "Susan",
        "age" => 32,
    ],
    "Database engineer" =>[
        "name" => "Jane",
        "age" => 23,
    ],
];

// use the same foreach loop
foreach ($members as $index => $member) {
    print "Array index : {$index}";
    print PHP_EOL;
    foreach ($member as $key => $value) {
        print "{$key} : {$value}";
        print PHP_EOL;
    }
}

The code above will produce the following output:

Array index : Front-end developer
name : Nathan
age : 29
Array index : Back-end developer
name : Susan
age : 32
Array index : Database engineer
name : Jane
age : 23

The PHP foreach construct allows you to loop through arrays.

When you have a multidimensional array, you can create two foreach statements.

The first loops through the containing array, then the second foreach loops through the child arrays.

You can use foreach to loop through numbered and associative multidimensional arrays.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.