Online training and video tutorials
Enter     Registration

Max Azimov
St. Petersburg

Articles [97]

User's video [259]

PHP 5 for Loops
PHP for loops execute a block of code a specified number of times.
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
  1. for (init counter; test counter; increment counter) {
  2.     code to be executed;
  3. }
  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
  1. <?php 
  2. for ($x = 0; $x <= 10; $x++) {
  3.     echo "The number is: $x <br>";
  4. ?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
  1. foreach ($array as $value) {
  2.     code to be executed;
  3. }
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 demonstrates a loop that will output the values of the given array ($colors):
  1. <?php 
  2. $colors = array("red", "green", "blue", "yellow"); 
  3. foreach ($colors as $value) {
  4.     echo "$value <br>";
  5. }
  6. ?>
You will learn more about arrays in a later chapter.


Map      Distance education, online learning courses. Project PLANETSTUDY - distance learning online.
© 2012 PlanetStudy


The site is a media provider
English USA
Australia Русский