Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

For loops in PHP

About for loops

For loops are a way we can run multiple iterations of something, in this case, repeat a block of code.

For loops have three different rules defined inside of them, the initial variable we use in our conditional, the conditional itself, and what we do with the variable after we’ve finished an iteration of the loop

Here’s an example of what a for loop looks like

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

We define our initial value i as 0.

We keep running our block of code over and over again until our value of i is equal to 4

Each time we reach the end of the loop, we add 1 to our variable i.

Using the break statement to leave a for loop early

We can leave a f0r loop earlier than our conditional value will allow using the break statement.

Using break we can leave the loop if i is equal to 2, even if our while loops condition states to go through the loop while i is less than 4

<?php
  for ($i = 0; i < 4; i++) {
    if($i == 2) {
      break;
    }
    echo $i;
  }
?>

Using the continue statement in a for loop

We may want to iterate through our loop but go back to the beginning of the loop at an earlier point. We can use the continue statement to do this. To show this, lets increment our loop twice and not show our echo

<?php
  for ($i = 0; i < 4; i++) {
    if($i == 1) {
       i+=2;
       continue; // the code below this wont run when i = 1
    }
    if($i == 2) {
      break;
    }
    echo $i;
  }
?>