PHP Loop
loop in PHP is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times.
- for − Loops through a block of code a specified number of times.
- foreach − Loops through a block of code for each element in an array.
- while − Loops through a block of code if and as long as a specified condition is true.
- do-while − Loops through a block of code once, and then repeats the loop as long as a special condition is true.
<?php // code to illustrate for loop for ($num = 1; $num <= 10; $num += 2) { echo "$num \n"; } ?>
initialization – Initialize the loop counter value. The initial value of the for loop is done only once. This parameter is optional.
condition – Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
Increment/decrement – It increments or decrements the value of the variable.