php loop through array – Best 7 Ways To Loop Through An Array In PHP?

Today, We want to share with you php loop through array.In this post we will show you php loop through array and echo, hear for PHP foreach multidimensional array we will give you demo and example for implement.In this post, we will learn about json to array php with an example.

php loop through array

Example 1 : PHP foreach Loop

<!DOCTYPE html>
<html>
<body>

<?php  
$members = array("Dasrath", "Ravan", "Indrajit", "Janaki"); 

foreach ($members as $value) {
  echo "$value <br>";
}
?>  

</body>
</html>

Example 2 : Use the PHP nested loop

Foreach loop through multidimensional array in PHP

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of Looping Over PHP Multidimensional Array</title>
</head>
<body>

<?php
// Multidimensional array
$members = array(
    "spider-man" => array(
        "name" => "Virat Parker",
        "email" => "[email protected]",
    ),
    "super-man" => array(
        "name" => "Mayur Dhameliya",
        "email" => "[email protected]",
    ),
    "iron-man" => array(
        "name" => "hariji demoliya",
        "email" => "[email protected]",
    )
);
 
// displaying all the keys and values one by one
$keys = array_keys($members);
for($i = 0; $i < count($members); $i++) {
    echo $keys[$i] . "{<br>";
    foreach($members[$keys[$i]] as $key => $value) {
        echo $key . " : " . $value . "<br>";
    }
    echo "}<br>";
}
?>

</body>
</html>

Example 3 : 1. While Loop

    $members = ["hanuman", "Ram", "Laxman", "Seeta", "Dasrath", "RedSauce"];
    $arrayLength = count($members);
    
    $i = 0;
    while ($i < $arrayLength)
    {
        echo $members[$i] ."<br />";
        $i++;
    }

Example 4 : For Loop

    $members = ["hanuman", "Ram", "Laxman", "Seeta", "Dasrath", "Ravan"];

    for ($i = 0; $i < count($members); $i++)  {
        echo $members[$i] ."<br />";
    }

Example 5 : Foreach Loop

       $members = ["hanuman", "Ram", "Laxman", "Seeta", "Dasrath"];

        foreach ($members as $member)  {
            echo $member ."<br />";
        }

Example 6 : Do While Loop

       $members = ["hanuman", "Ram", "Laxman", "Seeta", "Dasrath"];
        $i = 0;
        
        do {
            echo $members[$i] . "<br />";
            $i++;
        }
        while ($i < count($members));

Example 7 : Array Iterator

        $members = ["dharmik", "Bhavik", "Pratik", "Syam", "Dhaval"];
        
        $arrObject = new ArrayObject($members);
        $arrayIterator = $arrObject->getIterator();

        while( $arrayIterator->valid() )
        {
            echo $arrayIterator->current() . "<br />";
            $arrayIterator->next();
        }

I hope you get an idea about php loop through array.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.