Conditional Statements in PHP

conditional statements in PHP

Learning conditional statements in PHP will allow you to turn your ‘hello world’ program into something more useful. Conditional statements are the real magic behind programming. They allow your programs to act like they are intelligent. The most common conditional statement is “if-then”.

Conditional statements give you the power to control your program flow by branching. Branching is the ability to control a program to choose one of two or more tasks. Branching to change the flow of your program allows you to build a decision-making mechanism into your code. Decision making is the basis of simple AI (artificial intelligence). It allows your programs to act smarter with less code and fulfill multiple responsibilities.

In this article I will show you how to control your program using If/else statements and switch/case statements. When reading this you should see if you can get the program to compile and fail at various points along the way. The purpose is for the reader to be able to more easily grasp how branching works.

Code Samples

Simple If Statement

The ‘if’ keyword executes a block of code only when the condition inside the parenthesis is true.

<?php
    $secret = 7;
    if($secret == 7) {
        echo "You read my mind!";
    }
?>

In this example you can guess a secret number. You will only see the message if you guess correctly. To turn this into a game you can play – you can include this code in a web page with a form to submit your guess. We will write the full code after looking at a few more examples.

If-Else Statement: Adding the Else Clause

Most of the time you will want to run one block of code if the statement is true, and a different block of code if it is false. The else keyword lets you define that other block of code.

<?php
    $secret = 7;
    if($secret == 7) {
        echo "You read my mind!";
    } else {
        echo "Nope! Guess again...";
    }
?>

You can run more than one line of code – just make sure they are all between the open { and close } for that block. If you have several lines of code to execute in the block you may want to put your code into a function to keep your code from getting too complex and hard to read.

If – Else If – Else for More Complex Branching

You are not limited to only two paths. More complex branching can be created using the “else if” statement. In this example we will get the time of day and respond with an appropriate greeting.

<?php
    $hour = date("H");
    if($hour < 12) {
        echo "Good Morning";
    } else if($hour < 18) {
        echo "Good Afternoon";
    } else {
        echo "Good Evening";
    }
?>

First we set a variable “$hour” to equal the current hour on a 24 hour clock. (The date function is part of PHP and we will look at it more closely in a later tutorial. If you get unexpected results, it may be because the date function is picking up the time from your web server which may be different than your local timezone.)

Next we check to see if the hour is before noon and respond with “Good Morning” if is.

The next check will see if it is before 6pm (1800) and responds with a “Good Afternoon”. You might wonder how, if the hour is 9am you don’t see both “Good Morning” and “Good Afternoon”. The second if is only checked when the first one fails.

The final else statement only executes when the statements above it are false.

Multiple Else-If Statements

You can extend this example with as many hour/greeting combinations as you can think of… but as it grows, it gets harder to read and follow the logic.

<?php
    $hour = date("H");
    if($hour < 6) {
        echo "Where's my coffee?";
    } else if($hour < 12) {
        echo "Good Morning";
    } else if($hour < 18) {
        echo "Good Afternoon";
    } else if($hour < 21) {
        echo "Good Evening";
    } else {
        echo "Good Night";
    }
?>

This example works the same as the one before it, except with more branches – or choices. In the next example we will look at the same problem, but with a switch statement instead. Compare the readability between the two.

Switch Statement

We will start with the same steps as our previous example.

<?php
    $hour = date("H");
    switch($hour) {
      case 6:
        echo "Where's my coffee?";
        break;
      case 12:
        echo "Good Morning";
        break;
      case 18:
        echo "Good Afternoon";
        break;
      case 21:
        echo "Good Evening";
        break;
      default:
        echo "Good Night";
        break;
    }
?>

If you run this, odds are high that you will get “Good Night” regardless of the time of day. That is because in the switch/case the blocks of code are only executed when they are equal. In this example there are many hours of the day that are not accounted for.

Let’s fix that.

Additional Case Statements

The program will pass through the code in each case until it encounters the break statement. We will fix the problem with the previous code by adding a case statement for each of the possible hours.

<?php
    $hour = date("H");
    switch($hour) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
        echo "Where's my coffee? ";
        break;
      case 7:
      case 8:
      case 9:
      case 10:
      case 11:
      case 12:
        echo "Good Morning ";
        break;
      case 13:
      case 14:
      case 15:
      case 16:
      case 17:
      case 18:
        echo "Good Afternoon ";
        break;
      case 19:
      case 20:
      case 21:
        echo "Good Evening ";
        break;
      default:
        echo "Good Night ";
        break;
    }
?>

Now when you run the code in the early morning hours you will get the results you were expecting. When the hour matches one of our cases it will execute any code between the entrance time and the next break.

You may want to add a few more echo statements with or without the breaks to experiment with when they print out. I did not add suggestions in this sample code, because you will want to put them in the hours close to your current time when you test it.

Switch Case Statement with String Variables

You can see from the above that case statements above, if you have too many possibilities trying to manage all of them can be a challenge. In this example we will combine some if statements to set a string variable for our switch case to use.

<?php
    $hour = date("H");
    if($hour < 6) {
        $time_of_day = "early";
    } else if($hour < 12) {
        $time_of_day = "morning";
    } else if($hour < 18) {
        $time_of_day = "afternoon";
    } else if($hour < 21) {
        $time_of_day = "evening";
    } else {
        $time_of_day = "night";
    }

    switch($time_of_day) {
      case "early":
        echo "Where's my coffee?";
        break;
      case "morning":
        echo "Good Morning";
        break;
      case "afternoon":
        echo "Good Afternoon";
        break;
      case "night":
        echo "Good Evening";
        break;
      default:
        echo "Good Night";
        break;
    }
?>

I hope these examples can help you decide when to use if-else and when to use switch. For more examples of how switch is used check out the comments section of the official documentation page.

In general, if you are testing for ranges then use the if, if you have a limited set of options, then use switch.