Mixing conditional statements and loops in PHP

By Kongnyu Carine Last updated : December 11, 2023

As mentioned earlier, the looping statement is executing a particular code as long as a condition is true. On the order hand, conditional statements are statements that can only be executed based on the fulfillment of a particular condition(s).

Example

We have 3 phones and 3 laptops altogether 6 gadgets. Let's write a basic program that displays "phone" 3 times and "laptop" 3 times assuming the phones are labeled 1 to 3 and the laptops 4 to 6.

We are going to see how we can use the conditional statements and the loop statements to accomplish this. Since we have had a mastery of the syntaxes form the previous articles we will go straight to their implementation.

Using for loop and if...else

<?php
for ($l = 1; $l <= 6; $l++) {
    if ($l <= 3) {
        echo "<br>phone";
    } else {
        echo "<br>laptop";
    }
}
?>

Output

phone
phone
phone
laptop
laptop
laptop

Using while loop and if...else

<?php
$x = 1;
while ($x <= 6) {
    if ($x <= 3) {
        echo "<br>phone";
    } else {
        echo "<br>laptop";
    }
    $x++;
}
?>

Output

phone
phone
phone
laptop
laptop
laptop

Using do while loop and if...else

<?php
$x = 1;
do {
    if ($x <= 3) {
        echo "<br>phone";
    } else {
        echo "<br>laptop";
    }
    $x++;
} while ($x <= 6);
?>

Output

phone
phone
phone
laptop
laptop
laptop

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.