PHP - My SQL (Chapter - 4: PHP Conditions and Loops)

If, Else, Elseif, Switch, While, Do-While, For, Breaking Out of Loops

1. If


Growing up, the statement "you can have your dessert if you finish your vegetables first" was very familiar to me. It was an early introduction to the wonderful world of conditions, which are very common in our everyday lives. Whether we think about it or not, most decisions we make are based on at least one condition being met--or not met. Conditions are very important in programming.

The "if statement" is the most common conditional statement used in php. It will perform an action (such as serving dessert) if the specified condition is met, or true (such as finishing the vegetables). If the condition is not met, or false, the action will not be performed.

The if statement syntax places the condition in parenthesis, followed by the result in curly brackets, in the following manner: if (condition) { action to take }


<?php
     $number = 5;
      if ($number>3) { echo "Condition is met!"; }
?>

Remember in our last chapter how we studied php comparison operators? The "is greater than" comparison operator ">" is used in this example to compare two values. Our example, when translated to English, says: if the value of the numbers variable is greater than 3, echo that the condition is met. Since this particular condition is true, the action will be performed.
Conditions are not at all limited to comparing numerical values.


<?php
     $tell_joke = "yes";
      if ($tell_joke=="yes") {
        echo "How do you spot a modern spider?<br>";
        echo "She doesn't have a web she has a website!<br>";
    }
?>

The practical applications of if statements will become more clear as we progress, because we'll be seeing a lot more of them, beginning on the next page... or else!

2. Else


The if statement can be taken a step further with the else statement, used specifically as a follow-up to the if statement. What happens when an if statement is false? The else statement allows you to handle this possibility.

The else statement syntax is similar to the if statement syntax, but lacks a condition, and cannot be used alone. It must directly follow an if statement.

<?php
       $question = "What is the biggest ant in the world?";
      $answer = "An elephant!";
      if ($answer=="An elephant!") { echo "Yep, congrats."; }
      else { echo "Nope, sorry."; }
?>

In this example the condition is true (the answer is "An elephant!") so the else statement is ignored. If the condition was false, the else statement would be used:

<?php
     $age = 15;
     $discount_age = 60;
       if ($age>=$discount_age) {
             echo "Congratulations! You qualify for our senior discount.";
       } else {
             echo "Sorry, but you do not qualify for our senior discount.";
       }
?>

Now we see a condition stating that if the age is greater than or equal to the discount age, you would qualify for a senior discount, otherwise (else) you will not qualify. Unless you significantly raise the value of the age variable, there will be no senior discounts for you!

Next up we will learn how to add additional conditions into an if...else statement using elseif.

3. Elseif


If you like cheese you must be a mouse, else if you like lettuce you must be a rabbit, elseif you like chocolate you must be a human, else you must be a turtle. Yeah, that doesn't make much sense to me, either, but it's a fun way to get into the conditional programming mentality!

The elseif statement follows the if statement as a method of specifying (checking) alternative conditions to the if statement. Multiple elseif statements can be used.


<?php
$color = "orange";
     if ($color=="purple") {
        echo "Purple conveys royalty, nobility & wisdom.";
    } elseif ($color=="orange") {
        echo "Orange conveys energy, warmth & flamboyancy.";
    } elseif ($color=="blue") {
        echo "Blue conveys peace, tranquility & security.";
    } else {
        echo "I dunno what that color conveys, sorry.";
    }
?>

After examining the example, can you determine which block of code will be executed when this program is run? If you guessed "the orange one" then we have a winner!

When a true condition is reached, php will skip the remaining elseif and else statements in that block, meaning that since the orange condition was true, the blue condition is never checked and the else statement is ignored. The else statement is not required at the end, but should be used if there is any possibility of the condition(s) not being met.

Your homework assignment is to write a shopping list (fictional, if necessary) in php and give it to a parent or sibling. Even if they cannot critique the php you should have fun seeing what they make of the instructions.

4. Switch


Sometimes, multiple if/elseif/elseif statements are just not the most efficient option when checking for a specific condition. The switch statement can replace multiple if/elseif/elseif statements when you want to determine whether or not one value is equal to one of many other values in a more efficient manner.

The switch statement begins by accepting a single value, which it compares against multiple cases. When the case, or condition, is met (true), the specified block of code is executed, and the remainder of the switch statement is skipped.


<?php
     $time = "3 A.M.";
    switch ($time) {
        case "3 P.M.":
            echo "Good afternoon!";
            break;
        case "9 P.M.":
            echo "Good evening!";
            break;
        case "3 A.M.":
            echo "Good night!";
            break;
        case "9 A.M.":
            echo "Good morning!";
            break;
        default:
            echo "Hello!";
            break;
        }
?>

In our example, we begin by providing the switch statement with a value in the form of a variable. That value is compared against multiple cases, each of which contain their own value and end with a full colon rather than the standard semi-colon.

The switch statement accepts multiple lines of code in each block of code following each case, however our example only has a single line of code that should be run in the event that the case (condition) is true. Each block ends with a break to indicate that the remainder of the switch statement should be skipped after the case is true and the associated block of code is run.

The "default:" portion of the switch statement is similar to the else clause used with if statements. It determines what is to be done if none of the cases are true.

So do you know what the result of our switch statement is yet?

Good night!

5. While


Repetition is something that we all experience. Every night we go to bed, and every morning we get up. It is an endless cycle that loops back to begin all over again. When programming, it is very common to need to repeat the same task over and over again. You can either do this by hand (spending unnecessary time pounding on your keyboard) or you can use a loop.

PHP "while" loops will run a block of code over and over again as long as a condition is true. PHP "for" loops will run a block of code a specified number of times, which we will learn more about later.

First let's take a look at an example of a while loop, after which we will pick it apart and explain it:


<?php
    $count = 1;
     while ($count<=100) {
        echo $count . "<br>";
        $count++;
    }
?>

What does this code do? It echoes the numbers 1-100 with only one number per line. How do five lines of code produce 100 lines? Loops!

After setting a variable with a value of 1, our example sets up a loop that states "while the count is less than or equal to 100, run the following block of code". The block of code echoes the current value of the variable, then increases that value by 1. The loop performed this action until the value of $count was equal to 101, at which point in time the condition was no longer true and the loop was terminated.

A common mistake when running a loop like this is to forget to increment the value of the variable. This causes an endless loop running the exact same code over and over again, prompting eye-rolling, shaking of the head, and mutterings of "Oh, duh!". Trust me. I've been there. More than once.

6. Do-While


The do-while loop is very similar to the while loop, with one major difference. The condition is checked after running each loop instead of before. The "do" part comes before the "while" part, so the block of code is run once even if the condition is false.

An example is:


<?php
    $count = 1;
    do {
        echo $count . "<br>";
        $count++;
    }
    while ($count<=5);
?>

This example results in the numbers 1-5 being echoed on separate lines.

The do-while loop is not used often. At this point in my career, I have yet to use it, but now you know that it exists if you ever need it!

7. For


For loops can be used when you know in advance how many times a block of code should be run. They are more complex than while loops, but understandable once they are broken down and explained. They are more compact than while loops, making them popular for many uses.

Their syntax is: for (initialize; condition; increment) { action to take }

Instead of accepting only a single condition, like a while loop does, the for loop accepts three different expressions separated by semi-colons.

The first expression (initialize) sets, or initializes, a variable with a numerical value than can be used as a counter. When learning about "while" loops, we set this variable before the loop began, but "for" loops include this variable when beginning the loop. This expression is only run at the beginning of the loop, after which it is ignored.

The second expression is the condition, which behaves no different than the conditions that we have already discussed. It is checked at the beginning of every loop.

The third expression is the increment, which, in a while loop, is included as part of the action to be taken, but in a for loop is one of the expressions initially set. It is run each time the loop is run.

Let's see a for loop in action.


<?php
     $number = 75;
    for ($count=1; $count<=10; $count++) {
        echo $number . "<br>";
        $number += 75;
    }
?>

What our example is doing is using the $count variable as a counter to determine how many times the loop is run. It is set, evaluated, and incremented all in one statement. The block of code that follows simply echoes the current value of the $number variable, then adds 75 to that value. The loop is run 10 times, as specified in the condition.

The result will look like this:


75
150
225
300
375
450
525
600
675
750

For loops are fun to experiment with, and exhilarating when they actually do what you want them to for the first time ever!

8. Breaking Out of Loops


There will be time when you want to break out of, or end a loop before it is complete, usually when a certain condition is met. The break statement makes this possible.


<?php
    $number = 75;
    for ($count=1; $count<=10; $count++) {
        if ($number>300) { break; }
        echo $number . "<br>";
        $number += 75;
    }
?>

By adding a single line of code to the for loop that we have already examined, we can see the break statement in action. If the value of the number variable is greater than 300, the break statement is executed. When the break statement is executed, the loop is abruptly broken out of, so that the remaining code and remaining/unfinished loops are all ignored.

The result will be:


75
150
225
300

If multiple loops are nested, the break statement accepts a numerical value to indicate how many loops to break out of. The statement "break 1;" is the same as saying "break;", so to break out of two loop at once the correct statement is "break 2;" etc.


<?php
     $a = 0;
    $b = 7;
        while ($a<50) {
             for ($c=0; $c<3; $c++) {
                 $b = $b + $b - 2;
                 echo $b . "<br>";
                 if ($b>500) { break 2; }
             $a++;
         }
    }
?>

So in this example we see a while loop that contains a for loop that contains a condition saying "if the $b variable value is greater than 500, break out of 2 loops". Can you figure out what else this block of code is saying, and what the result will be?

I'll give you a hint:


12
22
42
82
162
322
642

Continue to Index

Welcome to HoneyBee - The Learning Platform

By Binit Patel

HoneyBee is a learning platform which is an integrated set of informative online services that enable learners involved in education with information, tools and resources to support and enhance Teaching, Learning and Management.

Contact With Me