Foreach loop through multidimensional array in PHP?

Foreach loop through multidimensional array in PHP?

Asked on November 3, 2018 in PHP.
Add Comment


  • 1 Answer(s)

    Here the PHP nested loop is used.

    The foreach loop is used in combination with the for loop to access all the keys, elements or values inside a PHP multidimensional array.

    For example:

    <?php
    // Multidimensional array
    $superheroes = array(
        "spider-man" => array(
        "name" => "Peter Parker",
        "email" => "[email protected]",
        ),
        "super-man" => array(
        "name" => "Clark Kent",
        "email" => "[email protected]",
        ),
        "iron-man" => array(
        "name" => "Harry Potter",
        "email" => "[email protected]",
        )
    );
     
    // 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>";
    }
    ?>
    
    Answered on November 3, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.