While loops in PHP

In this tutorial you will learn how to use a while loop in PHP. A while loop‘s syntax is slightly different to a for loop. A while loop will test a condition and will repeat a section of code inside the loop while that test condition evaluates to true. A while loop always tests the condition before running the code inside the loop (if the condition evaluates to true).

Unlike for loops, while loops do not have an inbuilt counter but you can include your own counter variable if you want to use one. While loops and for loops can often be used for the same purpose or to achieve the same goal. However, in different situations, one type of loop may be better than the other. For example, a for loop may be more efficient for going through each element in an array and when written may also express the statement in a clearer way.

Watch the video below and then scroll down to see the sample code for a PHP while loop.

Sample PHP code:

1
2
3
4
5
6
7
<?php
 $counter = 0;
 while($counter < 10){
 echo $counter , '</br>';
 $counter++;
 }
?>

PHP Manual references: