This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

3.4.4 Foreach Loop

  • The foreach loop - Loops through a block of code for each element in an array.

    The PHP foreach Loop

    The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

    Syntax

    foreach ($array as $value) {
      code to be executed;
    }

    For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

    Examples

    The following example will output the values of the given array ($colors):

    Example 1: PHP Loops - The PHP foreach Loop part 1
    <?php
    $colors = array("red", "green", "blue", "yellow");
    
    foreach ($colors as $value) {
      echo "$value <br>";
    }
    ?>

    The following example will output both the keys and the values of the given array ($age):

    Example 2: PHP Loops - The PHP foreach Loop part 2
    <?php
    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
    
    foreach($age as $x => $val) {
      echo "$x = $val<br>";
    }
    ?>

    You will learn more about arrays in the PHP Arrays chapter.

    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon

    Module 3 quiz