PHP Foreach Loop With Examples – PHP Loop Tutorial

  • PHP Foreach Loop With Examples – PHP Loop Tutorial

    Foreach is one of the advance loop feature provided by PHP. In this tutorial, we will explore in-depth of PHP foreach loop.

    You should have the basic understanding of PHP to understand this chapter. Before reading this tutorial you should read the following topic in a little bit deeper.

    1. PHP Array
    2. Class and Object in PHP

    foreach in php loop

    The Foreach loop is just another type of advance loop in PHP which we can use with array and object datatype. PHP internally manage the increment counter and initialization in foreach loop so you do not need to take help of initialization and increment like For Loop. If it is used to iterate other than object and array then it will throw an error.

    Foreach supports following two type of syntax:

    <pre><em><strong>foreach</strong>(array_expression/object <strong>as</strong> value)</em> <em>statement;</em></pre>

    And

    <pre>foreach(<em>array_expression/object <strong>as</strong>  key => value</em>) statement; </pre>

    Like other PHP loop construct, we can add multiple lines of the statement in foreach by clubbing the statement in curly braces.

    <pre>foreach(<em>array_expression/object <strong>as</strong>  key => value</em>)<strong>{</strong> statement1; statement2; statement3; <strong>}</strong></pre>

    For the better readability, we should always use curly braces with foreach. So that if you or someone else will debug your code after some time it will be readable. 

    Following is a basic foreach example
    $names = array('Ankur', 'John', 'Joy');
    foreach ($names as $name) { //foreach loop of name array
    print $name . ' ';
    }
    The above code will print “Ankur John Joy” on the screen.

    Now the same example with key value in foreach.
    $names = array('Ankur', 'John', 'Joy');
    foreach ($names as $key => $value) { //foreach with key value
    print $key . '=>' . $value . ',';
    }
    The above code will print 0=>Ankur,1=>John,2=>Joy, on the screen.

    So in the PHP Foreach to iterate we do not need any counter for initialization, increment and condition checking. It will iterate through ever element of collection internally and provide you the collection values for operation.

    Below is a flowchart of PHP Foreach loop.
    PHP Foreach

    In above flowchart, you can see that the Foreach construct check the array or object expression for its count.

    PHP Foreach Loop With Key and Value

    You can both key and value of the array by the foreach loop. You need to pass $key => $value both in the second part of the foreach construct.

    $array = array(2, 4, 6, 8);
    foreach ($array as $key => $value) {
    echo 'key is' . $key . ' & value is' . $value."\n";
    }

    It will print output:

    <pre id="line1">key is0 & value is2 <span id="line2"></span>key is1 & value is4 <span id="line3"></span>key is2 & value is6 <span id="line4"></span>key is3 & value is8</pre>

    Above example is printing key of the array which is 0,1,2,3.

    You can also use the foreach loop to iterate through the unsequential and non-integer key value pair like below:
    $array_complex = array(0=>'Ankur', 'fruit'=>'Orange', '5'=>'test', '9'=>'test2');
    foreach ($array_complex as $key => $value) {
    echo 'key is ' . $key . ' & value is ' . $value."\n";
    }

    The output of the above will:

    <pre id="line1">key is 0 & value is Ankur <span id="line2"></span>key is fruit & value is Orange <span id="line3"></span>key is 5 & value is test <span id="line4"></span>key is 9 & value is test2</pre>

    PHP Foreach loop by colon syntax

    PHP Foreach loop also supports the colon syntax.

    <pre><strong><em>foreach($array as key =>value):</em></strong> <em>statement;</em> <strong><em>endforeach;</em></strong></pre>

    Below is the simple example:
    $data_names = array('Ankur', 'John', 'Joe');
    foreach ($data_names as $key => $value):
    echo 'key is ' . $key . ' & value is ' . $value."\n";
    endforeach;

    Normally we use the colon syntax foreach in HTML. Let us suppose there is an array contains country names. Now you want to list the country as ordered list into your page then you can use the colon syntax in foreach like below.








      <?php
      $countries = array('India', 'USA', 'UK', 'France', 'Italy');
      foreach ($countries as $country):
      ?>
    1. <?php print $country ?>

    2. <?php
      endforeach;
      ?>


    Above Code will print order list of country like below.
    PHP Foreach Colon

    Nested Foreach and Multidimensional Array

    We can use the nested foreach. Normally we used the nested foreach for operation on a multidimensional array. But nested foreach is not limited to used with multidimensional array only. Multidimensional Array and nested foreach:
    $list_array = array( 1 => array('id' => '1010', 'name' => 'Ankur'), 2 => array('id' => '1020', 'name' => 'John'), 5 => array('id' => '1080', 'name' => 'Joe'), 9 => array('id' => '1007', 'name' => 'Test'), );
    foreach ($list_array as $array) {
    foreach ($array as $key => $value) {
    print 'Key=>' . $key . ' value=>' . $value . "\n";
    } print "\n";
    }
    Below is the output of above code.
    Nested Foreach
    So to operate on associative array we can use the nested foreach if required.

    Foreach With PHP Objects

    Foreach also works with object data type in PHP. It works on both stdClass objects as well as the normal PHP class object. In both stdClass and normal class objects, it iterates on the property of the object. In the normal class object, the foreach behavior works along with the visibility. If you will use foreach inside the class it will iterate to the public, private and protected properties. But if you will use foreach outside the class then it will iterate through only public properties.