PHP Loop through array

There are some methods to look through one array in PHP. The functions are foreach, while and for.  In this article, we will show examples on PHP loop through array using each of these functions. By these examples, there will be a loop in the PHP script, and on each member of the array, the PHP script will show its value.

Instead, any operation can be performed for each member of the array found.

PHP Loop through array using foreach()

The foreach function is one of the most used for looping in PHP. As the name says: “For each” member, do such tasks.


foreach ($array as $key)
    echo "Value: $key <br>";


Loop through a multidimensional array in PHP

The command foreach can be also used to look inside multidimensional arrays in PHP. Its usage will depend on the structure of the array.




// Let's build the array structure
$array[1]['name'] = "John";
$array[1]['phone'] = "+1 888 9567834";
$array[2]['name'] = "Doe";
$array[2]['phone'] = "+44 32 5600 673";
$array[3]['name'] = "Robert";
$array[3]['phone'] = "+1 45 5634 0843";
$array[4] = "Maria";

foreach ($array as $key1 => $value)
    echo "<br> Value: $key1 Value: $value<br>";
    // If it's an array, let's do another look inside it
    if (is_array($value))
        foreach ($value as $key2)
            echo "---- $key2 <br>";

    // if it's a simple string (non-array), let's print it
        echo "---- $value";


So, the output:

Value: 1 Value: Array
---- John 
---- +1 888 9567834 

Value: 2 Value: Array
---- Doe 
---- +44 32 5600 673 

Value: 3 Value: Array
---- Robert 
---- +1 45 5634 0843 

Value: 4 Value: Maria
---- Maria

In this example, $value on the first level of the array was brought as a new array. Then, you can run another foreach on this new array, to get its contents. We have used the is_array() PHP function to check whether it’s a simple string or an array.

More information about the foreach() functon can be found here.


Share and Enjoy !

0 0

Leave a Reply

Your email address will not be published. Required fields are marked *