PHP Tutorials

PHP for Loop Explained: Repeat Code with Examples

A PHP for loop lets you repeat a block of code while a condition stays true. This lesson breaks down the syntax and shows practical examples you can use right away.

Serhat ALPASLAN2 min read

for loop

With the for loop, you can make a block of code repeat according to a specific condition. Its syntax is as follows.

for (başlangıc; koşul ; artış ya da azalış) {
    /*  as long as the counter check part 
    returns true, the code is executed
    */
  }

Let’s go over the things to pay attention to in the syntax above.

  • Start : The for loop must have a starting point, that is, the value at which the code that will repeat begins.
  • Condition : The loop must end somehow, so we have to write the condition under which we want the loop to end.
  • Increment or Decrement : When we count from 1 to 10 there is a positive increment, or the exact opposite, we may need to count down from 10. So in this case we need to specify whether it will be an increment or a decrement.

Let’s understand it better with the following example.

 

<?php
$toplam= 0;
for ($i = 1; $i <= 10; $i++) {
	$toplam += $i ;
}
echo $toplam;

If we look at the example above, the starting point is set with $i = 1, and right after that a condition for the end is added, $i <= 10, and finally it’s decided whether there will be an increment or an end; here $i++ says it should increment. As output it will give us the result 55.

The for loop could also be written alternatively as follows. The only difference is in the way it’s written. So you can choose whichever style you prefer.

<?php
$toplam = 0;
for ($i = 1; $i <= 10; $i++):
	$toplam += $i;
endfor;
echo $toplam ;

The general preference is the form I showed in the first example.

Now let’s try a different example.

<?php
$r = 6;
$c = 8;
for ($i = 1; $i <= $r; $i++) {
    for ($j = 1; $j <= $c; $j++) {
        if ($i == 1 || $i == $r || $j == 1 || $j == $c)
            echo "* ";
        else
            echo "  ";
    }
    echo "\n";
}
?>

You can examine the output on your own computer by trying the example above. You can find more examples on the official PHP website.

Share it if it helped

Write a comment