Loops through a block of code a specified number of times, or when a specified condition is true.
The for loop is used when you know in advance the number of times the script needs to run.
for (initial value; condition; increment){code to be executed;}
parameter:
Initial value : Mainly initializes a variable value, used to set a counter (but can be any code that is executed once at the beginning of the loop).
Condition : Restriction conditions for loop execution. If TRUE, the loop continues. If FALSE, the loop ends.
Increment : Mainly used to increment a counter (but 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).
The following example defines a loop with an initial value of i=1. As long as variable i
is less than or equal to 5, the loop will continue to run. Each time the loop runs, variable i
will be incremented by 1:
<?php for ( $i = 1 ; $i <= 5 ; $i ++ ) { echo " The number is " . $i . " <br> " ; } ?>
Output:
The number is 1The number is 2The number is 3The number is 4The number is 5
The foreach loop is used to iterate over an array.
foreach ($array as $value){ Code to be executed;}
Each time you loop, the value of the current array element is assigned to the $value variable (the array pointer moves one by one), and the next time you loop, you see the next value in the array.
The following example demonstrates a loop that prints the values of a given array:
<?php $x = array ( " one " , " two " , " three " ) ; foreach ( $x as $value ) { echo $value . " <br> " ; } ?>
Output:
onetwothree