September 19, 2022
Share

Sometimes when writing our programs, we need them to do something over and over again. When this is the case, we use the loops. We have different types of loops but let us focus on the while and do loop.

While loop

It loops through a block of code as long as the specified condition is true. Let us get an example of a program that counts from 1 to 10

<?php
    $a = 1;

    while($a <= 10) {
        echo "The number is: $a <br>";
        $a++;
    }
?>

The program above starts with a variable $a that is assigned a value of 1, this will act as the starting value in the loop. We then start the while loop with the while keyword followed by the condition in bracket. The condition is $a is 10 or less. What this means is that we shall repeat running the code inside the curly brackets (The number is $a) as long the value in $a is still less than 10. $a++ is for incrementing the values from 1, 2, 3 up to 10. Therefore, as it is incrementing, it continuously checks to see if the new value is still less than or equal to 10. If it is, it stops the looping.

do...while

Loops through a block of code once, and then repeats the loop as long as the specified condition is true. The difference between this and the while loop is that for the do loop, it first runs the program once before it starts looping yet for the while loop, it immediately starts looping before executing the program. Let us modify the code above to utilize the do loop.

<?php
    $a = 1;

     do {
        echo "The number is: $a <br>";
        $a++;
    } while($a <= 10)
?>

That’s how we use loops in PHP. You can see how other loops like for loop and foreach loop are used. Loops are extremely important when working with databases especially when retrieving data from them.

Back To Top