PHP if...else Statements

Chapter 22 22 mins

Learning outcomes:

  1. A quick recap
  2. Nesting if and else statements
  3. The elseif statement
  4. Using logical operators

A quick recap

All the way back in the PHP Control Flow chapter, we learnt about the if and else statements. Let's quickly recap both of them.

Starting with if:

The if statement is used to execute a piece of code when a given condition is met.

Here's the syntax of if:

if (condition) statement;

Following the if keyword is the condition to test, enclosed in a pair of parentheses (()), followed by the statement to execute when the condition is met.

The condition is either a Boolean value itself (i.e true or false) or is coerced to a Boolean automatically by PHP before being evaluated. We'll see examples of this shortly below.

The former part of an if statement, i.e. the keyword followed by the condition, is often referred to as the header of if. Similarly, the latter part of the statement, i.e. the statement to execute, is referred to as the body of if.

Although there is no restriction to use a block statement, denoted via a pair of braces ({}), as the body of an if statement, we usually do so to favor readability and to, most importantly, get more than one statement to be executed when the underlying condition gets met.

This gives us the following syntax:

if (condition) {
   statement_1;
   statement_2;
   ...
   statement_n;
}

Time for some examples.

Suppose that we'd like to output a message to the user, asking him/her to go out with an umbrella if it is raining outside.

In the code below, the fact that it is raining today is represented by the Boolean variable is_raining, and based on its value, we make an alert to the user:

<?php

$is_raining = true;

if ($is_raining) {
   echo "Don't forget an umbrella!";
}
Don't forget an umbrella!

Try changing the value of $is_raining to false and then rerun the code — you shouldn't get any output this time.

We can use any valid expression as the condition of an if statement. It's quite customary to use Boolean and relational operators in the condition of an if statement.

As an example, in the code below, we log 'Even' if the given number $n is even:

<?php

$n = 10;

if ($n % 2 === 0) {
   echo 'Even';
}
Even

Indeed 10 is an even number, and thus we get the desired output.

In both the examples above, the if's conditions were expressions that directly evaluated to Boolean values. Sometimes, however, we might use an expression, for the condition, that returns a non-Boolean value.

In such cases, PHP coerces the expression's resolved value to the corresponding Boolean before making the decision as to whether to apply if or not.

For instance, in the code below, to check if the given array $arr is non-empty, we simply use count($arr) (that returns an integer), instead of something such as count($arr) !== 0 (that returns a Boolean).

<?php

$arr = [1, 10, 50];

if (count($arr)) {
   echo 'Array is non-empty';
}

This is because if the array is non-empty, then count($arr) would be a non-zero integer, and we already know by this point that non-zero integers coerce to the Boolean value true.

Even if we read out this code, it'll sound more readable than if we had used count($arr) !== 0. That is, it reads like 'if the array has a length, then do this', where 'has a length' means that the length is non-zero.

So this was all about if. Let's now review else.

Moving on, the else statement has the exact opposite behavior to an if statement.

When an if statement's condition fails, the corresponding else statement gets executed.

Here's the syntax of else:

if (condition) statement;
else statement;

The else keyword is followed by the statement to execute when the preceding if fails.

Remember that an else statement can't appear on its own; it has to have a preceding if statement.

This makes perfect sense, since even in English language, we use the word 'else' after we've made a preceding claim using 'if'. For instance, 'if this happens, then do this, or else do that'.

In the code below, we extend the rain-alert example shown above to make an output if there are no signs of rain today. Also we change $is_raining from true to false in order to test the else:

<?php

$is_raining = false;

if ($is_raining) {
   echo "Don't forget an umbrella!";
}
else {
   echo 'No need for an umbrella.';
}

Simple.

With this, our recap of if and else reaches its end. If conceptsAreStillUnclear(), then consider reviewing this section and the chapter PHP Control Flow.

Nesting if and else statements

As we know by this stage, the body of an if statement and an else statement can be any valid statement in PHP. Right?

Moreover, if we make the body a block statement (denoted via {}), we can put any number of statements within it. Isn't that so?

This takes us to the idea of nesting conditional statements.

Nesting conditional statements, i.e. putting conditional statements inside conditional statements, is very common, not just in PHP but in almost all high-level programming languages.

Let's consider a quick example.

Suppose we have an integer $n that is known to be a number in the range 0 - 100 (both inclusive). Our job is to determine if the number has a fractional part or is an integer (without a fractional part). If it's an integer, we have to further determine whether it's even or odd.

Now just by reading this description, we can immediately realize that we need an if statement to check whether $n is a fractional number (or maybe even go the other way and instead check if $n is an integral number). If it is a fractional number, we proceed as desired, or otherwise fall back to the else block.

Inside the else block, it's known that $n is an integer and, likewise, we lay out another set of if...else statements to check the parity of the integer, i.e. whether it's even or odd.

In the code below, we implement this program with the help of a function to help us test the whole logic on multiple numbers:

<?php

function test_number($n) {
   // Check if $n is a fractional number, i.e. with a
   // fractional part, such as 3.5, 50.001.
   if (is_float($n)) {
      echo "Fractional\n";
   }

   // At this stage, we assume that $n is an integer.
   else {
      if ($n % 2 === 0) {
         echo "Even integer\n";
      }
      else {
         echo "Odd integer\n";
      }
   }
}

test_number(2);
test_number(60.0005);
test_number(99);
Even integer Fractional Odd integer

The expression is_float($n) returns true if the provided value $n is a float. If that's the case, we output the text 'Fractional.'

However, if that's not the case, we assume that $n is an integer and lay out an additional check to determine whether it's even or odd. This additional check is represented by a set of if...else statements nested inside the else statement above.

Note that the same task above could've been accomplished by shifting the bodies of the outer if and else statements, and obviously also changing the condition of if.

In the code below, we demonstrate this idea:

<?php

function test_number($n) {
   // Check if $n is an integer, i.e. without a
   // fractional part, such as 3, 50, 100.
   if (is_int($n)) {
      if ($n % 2 === 0) {
         echo "Even integer\n";
      }
      else {
         echo "Odd integer\n";
      }
   }

   // At this stage, we assume that $n is a fractional number.
   else {
      echo "Fractional\n";
   }
}

test_number(2);
test_number(60.0005);
test_number(99);
Even integer Fractional Odd integer

The code has surely changed, but the underlying logic is still the same, as evident by the output produced.

The elseif statement

If we want to execute a piece of code when a given condition is met, we use if. Similarly, if we want a piece of code to execute when the condition fails, we use else.

So far, so good.

But what if there are more conditions to test for?

For instance, we might want to determine the age group that a person falls in: children in 0 - 14, youth in 15 - 24, adults in 25 - 64, and seniors in 65 and above.

This grouping of ages has been obtained from Statistics Canada's website.

Technically, this can be achieved by simply nesting all the subsequent conditions, after the first if condition, in subsequent else blocks.

To understand what this means, consider the following implementation of this program:

<?php

$age = 37;

if ($age <= 14) {
   // 0 - 14
   echo 'Children';
}
else {
   if ($age <= 24) {
      // 15 - 24
      echo 'Youth';
   }
   else {
      if ($age <= 64) {
         // 25 - 64
         echo 'Adults';
      }
      else {
         // 65 and above
         echo 'Seniors';
      }
   }
}
Adults

Notice how the second if condition (line 10) is nested inside the first else, and how the third condition (line 15) is nested inside the second else.

Although, at first glance, this code might seem complex, it really isn't.

When the first if fails, we consider another condition in its corresponding else block. When that second if fails as well, we consider yet another condition in its corresponding else block. We keep moving this away until we hit our last condition. At that point, the corresponding else defines the code to execute when neither condition is met.

At least for now, as we had just three conditions to test, and even those conditions had simple blocks of code associated with them, the code didn't turn out ugly.

However, if the number of conditions increases and their associated bodies become more and more complex, then this naive nesting approach would surely come at the cost of code clarity and readability.

So what to do?

Well, from the perspective of PHP, there are two solutions:

  1. Keep using the idea of nesting if...else statements but without using a block statement in all but the last else's body.
  2. Use the elseif statement.

Let's first reason about option 1 and then consider option 2.

Option 1 simply says that we can keep on using nested ifs inside subsequent elses, with one rule: excluding the last else, the body of all else statements won't be a block statement but an if directly.

In other words, we get to use a single phrase to denote another condition in a chain of if and else statements, and that is else if.

It's utterly important to realize the fact that else if is not a keyword in PHP; else if is just an else statement whose body is an if statement. That's it.

Technically, else if can't even be a keyword, as it contains a space in it which goes against identifier naming rules of PHP.

In the following snippet, we rewrite the code above using the else if approach:

<?php

$age = 37;

if ($age <= 14) {
   // 0 - 14
   echo 'Children';
}
else if ($age <= 24) {
   // 15 - 24
   echo 'Youth';
}
else if ($age <= 64) {
   // 25 - 64
   echo 'Adults';
}
else {
   // 65 and above
   echo 'Seniors';
}
Adults

See how readable this code is than the previous one. The body of every if statement and that of the last else statement is at the same level of indentation, giving us the impression that altogether all the statements make up a single logical unit of code.

Once again, remember that else if is just an else statement associated with the preceding if, containing another if in its body.

Based on this fact, the very last else statement in the code above (in line 12) doesn't belong to the very first if statement (in line 3). Instead the else in line 6 belongs to the very first if, while the if in line 9 is tied to the very last else.

Now, let's talk about the keyword elseif.

The elseif statement defines a piece of code to be executed when the preceding if or elseif fails and when its own condition gets fulfilled.

Theoretically, elseif is the same as else if (as we saw above).

Here's how we could express elseif syntactically:

if (condition_1) statement;
elseif (condition_2) statement;
elseif (condition_3) statement;
...
else statement;

There could be one or more elseif statements between a given set of if and else statements.

Actually, it's not required to have an else following elseif; it's just shown above in order to better illustrate the positioning of elseif between if and else.

Likewise, the following is also perfectly valid:

if (condition_1) statement;
elseif (condition_2) statement;
...
elseif (condition_n) statement;
It's a must for elseif to be preceded by an if or an elseif statement.

Let's rewrite the code above using elseif:

<?php

$age = 37;

if ($age <= 14) {
   // 0 - 14
   echo 'Children';
}
elseif ($age <= 24) {
   // 15 - 24
   echo 'Youth';
}
elseif ($age <= 64) {
   // 25 - 64
   echo 'Adults';
}
else {
   // 65 and above
   echo 'Seniors';
}
Adults

Everything is the same as before, just else if has now become elseif.

Using logical operators

Most of the times when working with the if family of statements, it's required to combine multiple conditions together and execute code based on whether some, or all, or none of them, are true.

Although this can be accomplished solely using if, elseif and else, if done this way, it would be totally inefficient and repetitive.

It's rather recommended to use logical operators in such cases. They are meant to connect multiple conditions together in a much more compact way.

Below we explore all the three logical operators in PHP — logical NOT (!), logical OR (||) and logical AND (&&) — along with an explanation of when to use each one.

The logical OR (||) operator

If you need to perform the same action if either of two given conditions are met, then it would be inefficient to use elseif to do so.

For instance, say you want to print 'Divisible' if the user enters a number that is divisible either by 2 or 3.

Doing so using an if and elseif statement would look something like this:

<?php

$num = 8;

if ($num % 2 == 0) {
   echo 'Divisible';
}
elseif ($num % 3 == 0) {
   echo 'Divisible';
}

See how the echo statement is repeated twice in each block.

It's only when the action for each of a list of conditions is different than that of another, that the if...elseif combination sounds sensible.

If the action for two or more conditions' fulfillment is the same, then it's much more efficient to use the logical OR (||) operator.

Recall that || returns true if either of its operators evaluates to true.

Using ||, the problem above can be solved much more neatly as follows:

<?php

$num = 8;

if ($num % 2 == 0 || $num % 3 == 0) {
   echo 'Divisible';
}

The if's condition would evaluate to true if either $num % 2 == 0 is true, or $num % 3 == 0 is true, or both are true.

See how much similar is the statement above to plain English: "If $num is divisible by 2 or 3, then print 'Divisible'."

A more practical-level example of where could || be used is illustrated below.

Write some code to construct a 3 x 3 matrix, that has all 1's in the first row and also in the first column, and 0 otherwise.

The following code has been already set up for you:

<?php

$matrix = [];

for ($i = 0; $i < 3; $i++) {
   array_push($matrix, []);
   for ($j = 0; $j > 3; $j++) {
      // Your code goes here...
   }
}
<?php

$matrix = [];

for ($i = 0; $i < 3; $i++) {
   array_push($matrix, []);
   for ($j = 0; $j < 3; $j++) {
      if ($i === 0 || $j === 0) {
         $matrix[$i][$j] = 1;
      }
      else {
         $matrix[$i][$j] = 0;
      }
   }
}

The logical AND (&&) operator

Sometimes, instead of checking for the truth of at least one condition in a list of multiple conditions as we did above, it's required to check the truth of all the conditions.

That is, we want to see whether all of them are fulfilled and only then execute a piece of code.

Suppose we want to print 'Divisible by 6' if a number $num is divisible by both 2 and 3.

Using just if...else, this can be accomplished as follows:

<?php

$num = 12;

if ($num % 2 === 0) {
   if ($num % 3 === 0) {
      echo 'Divisible by 6';
   }
}

If $num is divisible by 2, then it's further checked if it's also divisible by 3. If this is so, 'Divisible by 6' is printed.

As before, checking for the truth of multiple conditions, that are meant to produce the same outcome, using multiple if statements is inefficient — we have to write multiple if statements in increased level of indentations which unnecessarily complicates the code.

A much better way is to use the logical AND (&&) operator.

The && operator returns true if both of its operands evaluate to true. Otherwise, it returns false.

Let's rewrite the code above using &&:

<?php

$num = 12;

if ($num % 2 === 0 && $num % 3 === 0) {
   echo 'Divisible by 6';
}

Once again, see how similar the if statement here sounds to normal English: "If $num is divisible by 2 and 3, then print 'Divisible by 6'."

Time for a quick task.

Given two numbers $a and $b, check whether both of them are positive, and if they are, then print their sum.

The following code has been set up:

<?php

$a = 10;
$b = 20;

// Your code goes here.
<?php

$a = 10;
$b = 20;

if ($a > 0 && $b > 0) {
   echo $a + $b;
}

The logical NOT (!) operator

Performing an operation when a given condition is false is another common routine in conditional programming.

For example, a login form may show an error message if the entered credentials do not correspond to an account; or an online email marketing tool may block certain features if the user it not on a premium plan; and so on.

In short, the use cases where the negation of a given condition is required to be true are endless.

In such cases, it's really handy to use the logical NOT (!) operator.

Let's say we have an image editing software with two plans: premium and free. The premium one offers many advanced tools, whereas the free version has all of them disabled.

In a real-world scenario, we would check whether the user's version of the software is premium, and enable all the cool features only if it is. However, for now, we can emulate this whole idea using a Boolean variable $is_premium and a single if conditional.

The variable $is_premium specifies whether the current software is premium or not. What we want to do is print 'Not premium' if the current software's version is not premium, i.e is_premium is false.

One way to do so is to compare $is_premium with false:

<?php

$is_premium = false;

if ($is_premium == false) {
   echo 'Not premium';
}
Not premium

The code obviously works but it doesn't sound that natural.

A better sounding code is shown below, leveraging the logical NOT (!) operator:

<?php

$is_premium = false;

if (!$is_premium) {
   echo 'Not premium';
}

See how natural the if here sounds: "If the plan is not premium, print 'Not premium'."