Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

While Loops in PHP

Loops in PHP allow us to call a block of code many times over without having to write the same code over and over again.

For example, lets say we want to print out the number’s one two and three in the console.

<?php
  echo 1;
  echo 2;
  echo 3;
?>

With loops we could reduce the amount of console logs we call.

About the while loop

The while loop is a loop that doesn’t define how much iterations will be done. Our while loop will continue to iterate over and over again until its condition is no longer met.

For example:

<?php
  while(true) {
    echo "Hello world";
  }
?>

Will run over and over again in the console indefinitely

For our scenario we will need to set a variable number equal to zero. and the condition inside our while loop will be that our variable must be less than 4 when we’re deciding whether or not we should enter the while loops block of code enclosed by curly brackets { }

Note that we have to increment our variable otherwise we’ll end up in an infinite loop where our variable is always equal to 0.

<?php
  $i = 0;
  while($i < 4) {
    echo "This is iteration number: " + i";
    i++;
  }
?>

Using the break statement to leave a while loop early

We can leave a while 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
  $i = 0;
  while(i < 4) {
    echo "This is iteration number:" . i;
    if(i == 2) {
      break;
    }
    i++;
  }
?>
Remember that this echo value will be printed to our HTML markup, so you have to be careful not to leave echo calls that are used for debugging

Using the continue statement to avoid executing succeeding lines of code

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 console.log

<?php
  $i = 0;
  while(i < 4) {
    if(i == 1) {
       i+=2;
       continue; // the code below this wont run when i = 1
    }
    echo "This is iteration number: " . i;
    if(i == 2) {
      break;
    }
    i++;
  }
?>