Home » PHP

Mixing conditional statements and loops in PHP

In this article, we are going to learn how we can use together with the various conditional statements and loops in PHP programming language with examples?
Submitted by Kongnyu Carine, on May 24, 2019

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.