PHP for loop

3 min read

Similar to the while loop , the for loop can be used to execute statements as long as a particular condition is met. The syntax of the for loop is as follows:

<?php 
 for (init counter; test counter; increment counter) {
     instruction code to be executed;
 } 
 ?> 

An example would be:

<?php
for ($ i = 0; $i <10; $i++) {
echo "$i,";
}
?>

In the above example, an initialization is first defined, in which case the variable $i is initialized to the value 0. The condition of the loop is $i<10, i.e., the instructions of the loop are run through as long as this condition is fulfilled. The looping step is $i++ in the above case. This step is done after every loop of PHP, i.e., in the above example the value of variable $i is incremented by 1 after looping.

The start value, the condition and also the loop step are optional. That means you can define them, but you do not have to. A completely empty for loop works as well, even if it does not necessarily make much sense:

<?php
$i = 0;
for (;;) {// no initialitation, condition, or loop
if ($i >= 20) {// Break loop if $i >= 20
break; }
echo "$i,"; $i++;
} ?>

Breaking loop processes by using a break and continue commands

As with the while loop , the for loop can be looped by the break and continue commands. By means of break. the further loop through is interrupted and continue while a loop pass is skipped:

<?php
for ($i = 0; $i <20; $i++) {
if ($i == 13) {
echo " Thirteen is an unlucky number !!! <br>";
break;
}
echo "$i,";
}
?>

In the above example, the loop pass is aborted as soon as the number 13 is reached. If you change the looping step from $ i ++ to, eg $ i += 2, then $i will never get the number 13 and the even numbers will be returned up to 20.

Unlike break, continue only skips a single loop step:

<?php
for ($i = 0; $i < 20; $i++) {
if ($i == 13) {
echo " Thirteen is an unlucky number !!! <br>"; continue; }
echo "$i,";
}
?>

The difference to the while loop

The contrast to the previously presented while loop is only in the spelling. Using both types of loops, the same functionality can be implemented.

But because of the simpler syntax, the for loop is mostly used when counting up values. In a while loop, the start value, the condition, and the final loop step to increment the count variable are spread over three lines; for a for loop, all information is in one and the same line.

The while loop, on the other hand, is used more frequently if it is not clear in advance how many looping cycles are needed. For example, you may want to search a text file until a particular word is found. Or you go through a table in a database and want to output all lines.

« »