WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 for Loops



The PHP for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {
    code to be executed;
}

Parameters:

  • 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
Each of the parameter expressions can be empty or contain multiple expressions that are separated with commas. In the for statement, the parameters are separated with semicolons.

The example below displays the numbers from 0 to 5:

Example

<?php
for ($x = 0; $x <= 5; $x++) {
    echo "The number is: $x <br>";
}
?>
//Output
Value of a : 0
Value of a : 1
Value of a : 2
Value of a : 3
Value of a : 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.

Syntax

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

The first form loops over the array. On each iteration, the value of the current element is assigned to $value, and the array pointer is moved by one, until it reaches the last array element. The second form will additionally assign the current element's key to the $key variable on each iteration.

The following example demonstrates a loop that will output the values of the given array ($colors):

Example

<?php
$colors = array("white", "red", "pink", "yellow");

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