Q:

Foreach loop through multidimensional array in PHP

0

Foreach loop through multidimensional array in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the PHP nested loop

You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.

Let's take a look at the following example to understand how it basically works:

<?php
// Multidimensional array
$superheroes = array(
    "spider-man" => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
    ),
    "super-man" => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
    ),
    "iron-man" => array(
        "name" => "Harry Potter",
        "email" => "harrypotter@mail.com",
    )
);
 
// Printing all the keys and values one by one
$keys = array_keys($superheroes);
for($i = 0; $i < count($superheroes); $i++) {
    echo $keys[$i] . "{<br>";
    foreach($superheroes[$keys[$i]] as $key => $value) {
        echo $key . " : " . $value . "<br>";
    }
    echo "}<br>";
}
?>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Delete an Element from an Array in PHP... >>
<< How to get single value from an array in PHP...