WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 for Loops

Loop through the code block a specified number of times, or loop through the code block when the specified condition is true.


for loop

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

Syntax

  for     (initial value;     conditions;     Incremental)  
  { 
       Code to execute;  
 }  

Parameters:

  • Initial value : Mainly initialize a variable value to set a counter (but it can be any code that is executed once at the beginning of the loop).
  • Conditions : Restrictions for loop execution. If TRUE, the cycle continues. If FALSE, the cycle ends.
  • Increment : It is mainly used to increment the counter (but it can be any code that is executed at the end of the loop).

Note: The Initial value and Increment parameters above can be empty or have multiple expressions (separated by commas).

Example

The following example defines a loop with an initial value of i = 1. As long as the variable i is less than or equal to 5, the loop will continue to run. Each time the loop runs, the variable i is incremented by 1:

Examples

<?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br>"; } ?>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5


foreach loop

The foreach loop is used to iterate through an array.

Syntax

foreach ($array as $value)
{
    To execute the code;
}

Each time through the loop, the value of the current array element will be assigned to the $ value variable (the array pointer will move one by one). When the next loop is performed, you will see the next value in the array.

Example

The following example demonstrates a loop that outputs the values of a given array:

Example

<?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br>"; } ?>

Output:

one
two
three