Learn PHP Programming

A backend server scripting language, and a powerful tool for making dynamic and interactive Web pages. Learn each topic with examples and output.

PHP Introduction
Control Structures
Php Forms
Php Advanced

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.

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

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  echo "$value <br>";
}
?>
red
green
blue
yellow
    

Next chapter is while and do-while loop :)


Share this page on :

=