Conditional Control Flow in PHP Tutorial (with if, else..if, else, switch, match & the ternary operator)

In this tutorial we learn how to control the flow of our PHP application through conditional logic with if, else if, else and switch statements.

We also cover the alternative syntax for if and switch statements (often used in applications like WordPress) and the ternary operator for simple if/else statements.

Finally, we cover the new match expression that was introduced in PHP 8.

What is conditional control flow

PHP allow us to control the flow of our application by evaluating conditional expressions and executing sections of code based on the result.

As an example, let’s consider an application that allows a userbase. After registering, the user may log into their personal administration area and perform certain tasks.

The login process would be handled by the following (simplified) logic:

  1. Check the user’s email address and password against the database.
  2. If the user’s email and password is correct, let them through to the member area. If not, ask the user to retry.

Step 2 is our conditional logic. In code it would look something like the following.

Example: conditional logic
if username AND password == correct
    execute code for login
    execute code to redirect to member area
otherwise
    ask the user to try again

So, specific sections of code gets executed based on the outcome of the conditions.

How to use an if statement

An if statement consists of at least 3 tokens.

  • The if keyword.
  • A condition block for our condition, wrapped in () (parentheses)
  • An execution block for the logic we want to execute if the condition proves true, wrapped in {} (curly braces)
Syntax:
if (conditional expression)
{
    // execution code
}

The statement reads as follows:

if (condition is true), execute { code }.
Example: if statement
if (1 + 1 == 2)
{
    echo "Execution code has been executed.";
}

In the example above we evaulate if 1 + 1 equals 2. It does of course and so the interpreter will have permission to go into the code block between the curly braces and execute the echo statement.

How to use an else..if ladder

The else..if statement is an optional condition that allows us to evaluate more conditions when the if condition evaluates to false.

We simply write another if statement below our first one and seperate the two with the else keyword.

Syntax:
if (conditional expression)
{
    // execution statement
}
else
if (conditional expression)
{
    // execution statement
}

When the if statement’s condition proves false, the interpreter will evaluate the else if condition.

Example: else..if statement
if (false)
{
    echo "Main if statement";
}
else
if (true)
{
    echo "Secondary if statement (else..if)";
}

Because the if condition is false, the interpreter will move on to the next one in the group and evaluate its condition. If the condition proves true, like it does in the example, it will execute that statement’s execution block.

We are allowed to create as many else if statements as we need. That’s why it’s called a ladder.

Example: multiple else..if
$num = 1;

if ($num * $num == 10)
{
    echo "Main if statement";
}
else
if ($num * $num > 5)
{
    echo "Secondary if statement";
}
else
if ($num * $num > 0)
{
    echo "Tertiary if statement";
}

The interpreter will go down the ladder and execute any statement’s execution block if their condition proves true.

How to use an else fallback statement

The optional else statement works as a catch-all for anything that an if and/or else if doesn’t catch. Think of it as a last resort situation.

The else statement has no conditional expression, but does allow an execution code block.

Syntax:
if (conditional expression)
{
    // execution statement
}
else
{
    // catch-all
}
Example: else statement
$num = -1;

if ($num * $num == 10)
{
    echo "Main if statement";
}
else
if ($num * $num > 5)
{
    echo "Secondary if statement";
}
else
{
    echo "Catch anything that isn't covered by an if and/or else..if statement";
}

In the example above, the result of both if evaluations will be false so the code in the else fallback block will be executed.

Curly brace location

There are two conventions on where to place the opening curly brace in languages that use curly braces to define a statement’s local scope.

  • The opening brace on the same line as the header.
  • The opening brace on the line following the header.
Example: curly brace location
if (true) {
    // same line curly brace
}

if (true)
{
    // seperate line curly brace
}

Which curly brace location to use

The convention in PHP is to write the curly brace on the same line as the header, but it’s up to you. The important thing is to stay consistent.

In this course we will follow the PHP convention and recommend you do too.

How to nest if, else..if and else statements

At times we will need to evaluate conditions based on the results of a prior condition.

PHP allows nesting conditions and it’s as simple as placing an if statement inside another if statement.

Syntax:
if (conditional expression) {
    // execution statement

    if (conditional expression) {
        // execution statement
    }
}
Example: nested conditional statements
if (true) {
    echo "Main if statement";
    echo "<br>";

    if (false) {
        echo "Nested if statement";
    } else {
        echo "Nested else statement";
    }
}

The interpreter will parse the code hierarchically, which means if the outer if statement’s condition proves true, it will move to the inner statements and process them before moving on to any outer else conditions.

note Even though we are allowed to nest as deeply as we want, we shouldn’t. A general rule of thumb is that if we need to nest more than 3 levels deep, we should try a different approach.

How to use a switch statement

A switch statement is essentially a series of if statements on the same condition.

As an example, let’s consider that we need to evaluate if a number is between 1 and 10. For every number, we want to execute different statements.

In a normal if grouping it would look as follows.

Example: if
$num = 5;

if ($num == 1) {
    echo $num;
} else if ($num == 2) {
    echo $num;
} else if ($num == 3) {
    echo $num;
} else if ($num == 4) {
    echo $num;
} else if ($num == 5) {
    echo $num;
} else if ($num == 6) {
    echo $num;
}
// etc...

While the example above is perfectly fine, it’s difficult to read at a glance and it’s a lot of typing. Specially if we consider that the evaluation expression only changes slightly each time.

This is where a switch statement comes in handy. Let’s consider that same example, but as a switch instead of an if statement.

Example: switch
$num = 2;

switch ($num) {
    case 1:
        echo $num;
        break;
    case 2:
        echo $num;
        break;
    case 3:
        echo $num;
        break;
    // etc...
}

The code is much cleaner, reads clearer and there is also less typing. But on the other hand, the code is less compact.

Consider a simpler switch statement.

Example: switch statement
$num = 1;

switch ($num) {
    case 1:
        echo $num;
        break;
}

Now let’s break it down step by step.

  1. First, we use the switch keyword.
  2. Then in parentheses, we write the value that we want to compare to other values. In this case we want to check if something matches the value of $num .
  3. Then we define scope for the evaluations with open and close curly braces.
  4. Next we define our comparison cases. We do this with the case keyword, followed by the comparison value and a colon.

    The statement reads: if $num == 1, then do what comes after the colon operator

  5. Following the colon operator, we provide the execution statements. In this case we simply echo the value of $num .

  6. Lastly, we use the break control statement to break out of the switch. We’re telling the interpreter that we found what we were looking for so it should stop executing the switch and move on to code outside and below it.

We will look at control statements after loops in the Control Statements lesson because they are used with both conditional and looping control flow.

note The switch statement evaluates with loose comparisons (==). It doesn’t check the type of the value.

The default case

We can specify a fallback case if none of the other cases match. It’s the switch statement’s version of an else clause.

Instead of writing the case keyword, we use default without a value. For the execution block we specify the fallback behavior and break out of the switch.

Example: default
$num = 1;
$msg = "";

switch ($num) {
    case 0:
        $msg = "False";
        break;
    case 1:
        $msg = "True";
        break;
   default:
        $msg = "Unknown";
        break;
}

echo $msg

Fallthrough conditions

The switch statement in PHP also allows for fallthrough conditions. These are basically case combinations.

Example: fallthrough conditions
$num = 1;
$msg = "";

switch ($num) {
    case -1:
    case  0:
        $msg = "False";
        break;
    case 1:
        $msg = "True";
        break;
  default:
        $msg = "Unknown";
        break;
}

echo $msg

We combine the -1 case with the 0 case by simply leaving out its logic.

The match expression

PHP 8 added a new conditional statement called the match expression . It’s similar to the switch statement, but offers a more concise syntax, among other improvements.

Consider the following statement.

Example: switch
$num = 1;
$msg = "";

switch ($num) {
    case 0:
        $msg = "False";
        break;
    case 1:
        $msg = "True";
        break;
  default:
        $msg = "Unknown";
        break;
}

echo $msg

Now let’s see the same statement rewritten as a match expression.

Example: match
$msg = match ($num) {
    0 => "False",
    1 => "True",
    default => "Unknown",
};

echo $msg

Let’s see the syntax differences.

  • It returns a value that can be stored or ignored.
  • Cases (also called arms) have a case => value structure and are separated with a comma.
  • The break control statement isn’t used.
  • The expression is terminated with a semicolon.

Along with a more concise syntax, the match expression offers the following benefits.

Stricter Comparisons

Types can’t be matched by mistake because the expression uses strict comparisons with the === operator, instead of the == operator that a switch uses.

Cases can be combined

The match expression doesn’t allow for fallthrough conditions. But it does allow combination conditions, which is essentially the same thing.

Example: combination conditions
// switch fallthrough
switch ($num) {
    case -1:
    case  0:
        $msg = "False";
        break;
}

// match combination
$msg = match ($num) {
    -1, 0 => "False"
};

Unhandled values throw an error

If we don’t specify a default and the match expression encounters an unknown value, the interpreter will throw an UnhandledMatchError error.

Example: unhandled match
$msg = match (5) {
    0 => "False",
    1 => "True",
};
Output: UnhandledMatchError
Fatal error: Uncaught UnhandledMatchError: Unhandled match value of type int

Exceptions

In PHP 8, throw changed from being a statement to an expression. That means we can throw exceptions directly from a match expression’s arm.

Example: throw
$msg = match (-1) {
    -1 => throw new EndTimesError(),
     0 => "False",
     1 => "True",
    default => "Unknown"
};

Switch vs. Match. Which one do we use?

It will mostly depend on the situation and your preference.

  • Even though the syntax is longer and more verbose, a switch reads easier at a glance.
  • A match also doesn’t allow for multiline code blocks yet, so a switch would then be the only option (apart from the if block of course).

We prefer to use switch/match as sparingly as possible in any language that supports it. There are usually other design patterns or more efficient solutions that can solve a problem we’re facing.

Alternative if and switch syntax

PHP offers an alternative syntax for two of its control structures, allowing us to more easily interact with other languages.

If you are familiar with templating languages like liquid, this type of syntax will feel familiar to you.

The alternative syntax replaces the opening curly brace with a : (colon) and the closing curly brace with an ending keyword, which differs between if and switch.

The ending keyword for an if statement is endif .

Syntax: alternative if
// Alternative if
if (expression):
	// execution block
endif;

// Inline alternative if
<?php if (condition): ?>
// execution
<?php endif ?>
Example: alternative if
<?php

if (true):
    echo "Alternative if syntax example 1";
endif;

?>

<?php if (true): ?>
<p>Alternative if syntax example 2</p>
<?php endif; ?>

In the case of a switch statement, the ending keyword becomes endswitch .

Example: alternative switch statement
<?php switch (1): ?>
<?php case 1: ?>
<p>We've found a match!</p>
<?php endswitch; ?>

The ternary operator as shorthand for if

PHP offers us the ternary operator as a shorter way to write an if/else statement that only has one execution statement each.

As an example, let’s consider a simple if statement.

Example:
if (true) { echo "True"; }
else      { echo "False";}

Both the if and else clause only contain a single execution statement each. If this is the case we can write a shorthand version of it with a ternary.

The ternary starts with our conditional expression, followed by a ? (question mark). Then we specify the execution code if the condition proves true, followed by a : (colon) and the execution code if the expression evaluates to false.

Syntax:
expression ? execution_if_true : execution_if_false;

The result can be used directly or stored in a data container.

Example: ternary operator
// Used directly
echo true ? "True": "False";

// Stored
$result = true ? "True": "False";

// The ternary reads as follows

//    if (true)  { "True" } else { "False" }
$result = true ?   "True"    :     "False";

Summary: Points to remember

  • Control flow is when we execute code based on the result of a condition.
  • An if statement consists of at least 3 tokens. The if keyword, the condition block and the execution block.
  • The else..if ladder handles follow up conditions that aren’t be expressed in the if statement.
    • The else..if ladder cannot stand on its own and must follow an if statement
  • The else fallback handles any other situation that the if and else..if ladder doesn’t cover.
    • The else fallback does not use a condition block and cannot stand on its own, it must follow either an if statement or an else..if ladder.
  • PHP’s convention is to write opening curly braces on the same line as the statement header.
  • Switch statements evaluate one value agains many cases.
    • After each case, we have to break out of the switch with the break control statement.
    • Case logic can be multi-line execution blocks and can contain other conditional statements.
    • While not required, we should include a fallback default value at the end of our switch statements.
    • Cases can be combined by removing their execution blocks and break control statements.
    • Switch statements evaluate with a loose comparison operator (==).
  • Conditional statements can be nested inside other conditional statements, they will be evaluated hierarchically.
    • If we find ourselves nesting more than 3 levels deep, we should refactor the code and try to find another solution.
  • The match expression is a shorthand for the switch statement.
    • It’s cases are written in a case => value structure and arms are separated with a comma.
    • We do not use the break control statement.
    • Cases are combined by removing their logic.
    • Match expressions cannot hold multi-line execution blocks.
    • Match expressions evaluate with a strict comparison operator (===).
    • Because it’s an expression, the statement must be terminated with a semicolon.
  • The if and switch statements have an alternative syntax where the opening curly brace is replaced with a colon and the closing curly brace is replaced with an ending keyword ( endif / endswitch ).
  • The ternary expression is a shorthand for if/else statements that have only single execution statements.
    • The ternary starts with the condition, followed by a question mark. Then we specify the single true/false execution statements separated by a colon.