CommonLounge Archive

PHP: If, Else, Elseif and Switch Statements

September 19, 2018

In this tutorial, you’ll learn about if-statements, using which you can do certain things only if certain conditions are met. In plain English, if-statements correspond to “Do this; then do that.” or “If this condition is true, perform this action; otherwise, do that action.”

A good way to visualize if-statements is flow charts. If-statements represent the yes / no questions in the flowchart below.

Before getting into if-statements, you’ll first learn how to compare things in PHP as well as the Boolean data type (values true and false). At the end of the lesson, you’ll also see switch statements, which are an alternative to the if-statements.

Compare things

A big part of programming involves comparing things. What’s the easiest thing to compare? Numbers, of course. Let’s see how that works:

<?php
    var_dump(5 > 2); // prints bool(true)
    echo "<br>";
    var_dump(3 < 1); // prints bool(false)
    echo "<br>";
    var_dump(5 > 2 * 2); // prints bool(true)
    echo "<br>";
    var_dump(1 == 1); // prints bool(true)
    echo "<br>";
    var_dump(5 != 2); // prints bool(true)
?>

We gave PHP some numbers to compare. As you can see, not only can PHP compare numbers, but it can also compare method results. Nice, huh?

We are using var_dump() to display the boolean values because using echo has some quirks. echo true prints 1 and echo false does nothing.

Do you wonder why we put two equal signs == next to each other to compare if numbers are equal? We use a single = for assigning values to variables. You always, always need to put two of them – ==– if you want to check if things are equal to each other. We can also state that things are unequal to each other. For that, we use the symbol !=, as shown in the example above.

Give PHP two more tasks:

echo "<br>";
var_dump(6 >= 12 / 2); // prints bool(true)
echo "<br>";
var_dump(3 <= 2); // prints bool(false)

We’ve seen > and <, but what do >= and <= mean? Read them like this:

  • x > y means: x is greater than y
  • x < y means: x is less than y
  • x <= y means: x is less than or equal to y
  • x >= y means: x is greater than or equal to y

We’ve summarized the list of comparison operators in PHP in a table at the end of the article.

Logical operators

PHP also has logical operators which allows us to combine multiple comparison. You can give PHP as many numbers to compare as you want, and it will give you an answer! The following are the logical operators:

  • and operator (&&) – if you use the && operator, both comparisons have to be true in order for the whole expression to be true.
  • or operator (||) – if you use the || operator, only one of the comparisons has to be true in order for the whole expression to be true
  • not operator (!) - if you use the ! operator, it inverts the value of the expression

Here are some examples:

echo "<br>";
var_dump(6 > 2 && 3 > 1);
// prints bool(true) (both sides are true)
echo "<br>";
var_dump(3 > 2 && 2 < 1);
// prints bool(false) (true and false is false)
echo "<br>";
var_dump(4 > 5 || 9 < 17);
// prints bool(true) (false and true is true)
echo "<br>";
var_dump(!(5 > 2));
// prints bool(false) (= not true)
echo "<br>";
var_dump(!(2 > 5));
// prints bool(true) (= not false)

As we’ve done with examples before, let’s see the step-by-step evaluation of one of the above expressions to make sure everything is crystal clear.

3 > 2 && 2 < 1
=> true && 2 < 1
=> true && false
=> false

Boolean

Incidentally, you just learned about a new type of data in PHP. It’s called Boolean.

There are only two Boolean values:

  • true
  • false

In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. For PHP to understand a boolean value, you can write it as True , true, TRUE, and **tRUE**. All of them work! (The same applies to False as well, of course.) However, the convention is to use all lowercase (true and false), as we have been doing.

Booleans can be variables, too! See here:

<?php
    $b = true;
    var_dump($b); // prints bool(true)
?>

You can also do it this way:

<?php
    $a = 2 > 5;
    var_dump($a); // prints bool(false)
?>

Practice and have fun with Booleans by trying to print the following expressions using var_dump():

  • true && true
  • false && true
  • true || 1 == 1
  • 1 != 2

Congrats! Booleans are one of the coolest features in programming, and you just learned how to use them!

You can now move on to an essential tool in programming:

If … else … elseif

If statement

Lots of things in code should be executed only when given conditions are met. That’s why PHP has something called if statement.

Add this code in your file index.php (located in your basics folder inside htdocs):

<?php
    if (3 > 2) {
        echo "<h1>It Works!</h1>"; // prints 'It Works!' wrapped within h1 tag
    }
?>

Notice how we’ve indented the next line of code by 4 spaces and added curly braces after the if statement? We need to do this so PHP knows what code to run if the condition is true. You can do one space, but nearly all PHP programmers use 4 to make things look neat. A single tab will also count as 4 spaces.

Save it and give it a run!

In general, the syntax for an if statement is:

<?php
    if (/* condition to check */) {
        /* things to do if condition is true */
        /* as many statements as you want */ 
        /* make sure all statements are inside the curly braces { } */ 
    }
?>

What if a condition isn’t true? If … else

In the previous example, the code was executed only when the condition was true. But PHP also has elseif and else statements:

<?php
    if (5 > 2) {
        echo "<h1>5 is indeed greater than 2</h1>";
    } else {
        echo "<h1>5 is not greater than 2</h1>";
    }
?>

When this is run it will print out:

5 is indeed greater than 2

If 2 was a greater number than 5, then the second command would be executed.

If … elseif … else

Let’s see how elseif works:

<?php
    $name = 'Dave';
    if ($name == 'Commonlounge') {
        echo "<h1>Hey Commonlounge!</h1>";
    } elseif ($name == 'Dave') {
        echo "<h1>Hey Dave!</h1>";
    } else {
        echo "<h1>Hey anonymous!</h1>";
    }
?>

and executed:

Hey Dave!

See what happened there? elseif lets you add extra conditions that run if the previous conditions fail.

You can add as many elseif statements as you like after your initial if statement. For example:

<?php
    $volume = 57;
    if ($volume < 20) {
        echo "It's kinda quiet.";
    } elseif ($volume >= 20 && $volume < 40) {
        echo "It's nice for background music";
    } elseif ($volume >= 40 && $volume < 60) {
        echo "Perfect, I can hear all the details";
    } elseif ($volume >= 60 && $volume < 80) {
        echo "Nice for parties";
    } elseif ($volume >= 80 && $volume < 100) {
        echo "A bit loud!";
    } else {
        echo "My ears are hurting! :(";
    }
?>

PHP runs through each test in sequence and prints:

Perfect, I can hear all the details

Note that in a chain if … else if … else statements, only the first condition that is met gets executed. As soon as the first condition is met, none of future else (or elseif) conditions will be considered. Hence, the above code could be written more concisely as:

<?php
    $volume = 57;
    if ($volume < 20) {
        echo "It's kinda quiet.";
    } elseif ($volume < 40) {
        echo "It's nice for background music";
    } elseif ($volume < 60) {
        echo "Perfect, I can hear all the details";
    } elseif ($volume < 80) {
        echo "Nice for parties";
    } elseif ($volume < 100) {
        echo "A bit loud!";
    } else {
        echo "My ears are hurting! :(";
    }
?>

We’re making use of the fact that, when we compare volume < 60 (for example), all the previous conditions must have been False. This automatically implies that volume >= 40 (since the first two conditions were False). The code might be slightly harder to read, but it is equivalent to the previous one.


Switch

The switch statement is used to perform different actions based on the value of a specific variable. It can sometimes be used as a substitute for the if statement.

The following example shows us an example of the switch statement, and then it shows us the equivalent using if and elseif statements:

$i = 20;
// example of switch statement   
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 10:
        echo "i equals 10";
        break;
    case 20:
        echo "i equals 20";
        break;
}
// prints 'i equals 20'
equivalent code using if ... elseif statements
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 10) {
    echo "i equals 10";
} elseif ($i == 20) {
    echo "i equals 20";
}
// prints 'i equals 20'

Let’s understand how the switch statement is executed. The switch statement executes line by line. First, we evaluate the value given to the switch expression (in this case i = 20 so switch($i) has value 20).

Since the value is 20, the code execution goes to the statement saying case 20 and starts executing any following lines. PHP continues to execute the lines until the end of the switch block, or the first time it sees a break statement. In our example, since i was equal to 20, the code jumps to the part where it says case 20: and prints i equals 20 to the browser. After printing, PHP encounters the break statement and therefore stops executing the switch block.

Break statements

If you don’t write a break statement at the end of a case block, PHP will go on executing the statements of the following case. For example:

$i = 0;
switch ($i) {
    case 0:
        echo "i equals 0";
    case 10:
        echo "i equals 10";
    case 20:
        echo "i equals 20";
        break;
}
// prints 'i equals 0i equals 10i equals 20'

Thus, it is important not to forget break statements as it can give us an undesired output.

Fall-through switch

On the contrary, not writing break statements (well, intentionally) can sometimes be useful too. For example:

$i = 0;
switch ($i) {
    case 0:
    case 1:
    case 2:
        echo "i is less than 3 but not negative";
        break;
    case 3:
        echo "i is 3";
        break;
}
// prints 'i is less than 3 but not negative'

Here, when we set i = 0, PHP goes to case 0 and finds nothing there. It then goes to the next line and again to the next line until it sees the echo function. i is less than 3 but not negative is therefore printed. Finally, PHP sees the break statement and comes out of the switch block.

What we just saw is called a fall-through switch. As the name suggests, it is a switch case that keeps falling through to the next case until it finds something to execute and breaks out of the switch block.

Default block

Most of the time, you’ll want to run specific code for particular cases, and some kind of “normal situation” code for any other cases. Let’s say that the code above deals with a value from 1 to 10; instead of filling in all the missing cases, we can simply give a default:

$i = 7;
switch ($i) {
    case 0:
    case 1:
    case 2:
        echo "i is less than 3 but not negative";
        break;
    case 3:
        echo "i is 3";
        break;
    default:
        echo "i is greater than 3";
}

This prints:

i is greater than 3

Note that break statement is not necessary after default as PHP anyways doesn’t have anything else to execute after echo and therefore, comes out of the switch block.

Summary

In the last few exercises you learned about:

  • comparing things – in PHP you can compare things by using >, >=, ==, <=, < and the &&, || operators
  • Boolean – a type of object that can only have one of two values: true or false
  • if … elseif … else – statements that allow you to execute code only when certain conditions are met.
  • switch - an alternative to if else statements.

Appendix: List of Comparison Operators

The following is a list of all comparison operations supported by PHP.

Operator | Example | Result | Description 
---------|---------|--------|--------------------------------
   ==    | 4 == 5  | false  | is equal to
   !=    | 4 != 5  | true   | is not equal to
   >     | 4 > 5   | false  | is greater than
   <     | 4 < 5   | true   | is less than 
   >=    | 4 >= 5  | false  | is greater than or equal to
   <=    | 4 <= 5  | true   | is less than or equal to

Appendix: List of Boolean Operators

The following is a list of all boolean operations supported by PHP.

Operator | Examples        | Result | Description 
=========|=================|========|====================================
  &&     | 3 < 4 && 5 < 4  | false  | true if both values are true
         | 3 < 4 && 5 > 4  | true   | 
---------|-----------------|--------|------------------------------------
  ||     | 3 < 4 || 5 < 4  | true   | true if at-least one value is true
         | 3 > 4 || 5 < 4  | false  | 
---------|-----------------|--------|------------------------------------
   !     | ! False         | true   | inverts the value 
         | ! True          | false  | 

Time for a quiz and then the last part of this section!


© 2016-2022. All rights reserved.