PHP if, else, switch & ternary Conditional Control Flow Tutorial

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.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is conditional control flow

PHP allow us to control the flow of our application by evaluating conditional expressions. Based on the evaluation result, the interpreter will execute specific code statements.

As an example, let’s consider an application that allows a user base. 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 number 2 is our conditional logic, in code it would look something like this:

  • if username && password == correct
    • execute code for login
    • execute code to redirect to personal administration area
  • otherwise
    • ask user to try again

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

How to write an if statement

The first part of the conditional control logic is the if statement.

When writing the if statement we need two things:

  • A section for the condition
  • A section for the code to execute, if the condition evaluates to true

Our condition expression is wrapped in parentheses and our execution statement is wrapped in curly braces. The execution portion of the if statement is called a code block.

Syntax:
if (conditional expression)
{
    execution expression
}

The statement reads as follows:if conditional expression inside parentheses is true, execute the statement in the code block between the curly braces.

Example: if statement
<?php

if (1 + 1 == 2)
{
    echo "Execution code has been executed.";
}

?>

In the example above we, evaluate if1 + 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 write an else if statement

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

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

Syntax:
if (conditional expression)
{
    execution statement
}
else
if (conditional expression)
{
	execution statement
}
Example: else...if statement
<?php

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

?>

In the example above, we purposely modify the conditional code to execute the secondary if statement.

When the interpreter realizes that the if condition is false, it doesn’t have permission to execute its code block and so moves on to evaluate the else if statement.

We don’t always need to specify code in else if. If we don’t need to evaluate another condition, we can simply write the rest of our code below the if statement code block.

Example:
<?php

if (true)
{
    echo "Main if statement";
}

echo "<br>This statement is outside of
the if scope and will execute once
the interpreter has finished parsing
the if statement.";

?>

Everything inside the curly braces is in the if statement’s scope, when we move outside the curly braces we are outside the scope and the interpreter can resume normal operations.

PHP allows us to have multiple else if statements connected to an if statement.

Example:
<?php

$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";
}

?>

How to write an else 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
<?php

$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 evaluations will be false, and because we can’t always specify each fallback condition in an else if, we include the else to catch anything we didn’t specify.

A note on curly brace location

There are two conventions, in languages that use curly braces to define scope, of where to place the first curly brace.

Some programmers write the first curly brace on the same line as the if statement, others write the curly brace on its own line directly beneath the if statement.

Example:
<?php

if (true) {
    # same line curly brace
}

if (true)
{
    # separate line curly brace
}

?>

Typically, you will find that programmers coming from the C family (C, C++, C#) will write their curly braces on separate lines.

Programmers that come from languages such as Javascript, will write their curly braces on the same line, as the same line curly brace is the dominant convention in Javascript.

Which curly brace location to use

Which to choose is up to you, or the framework you use, or the conventions an employer may lay out for you. Try both and choose the one that is the most comfortable to you.

We generally prefer curly braces on their own lines because the code looks cleaner, albeit less compact, and is therefore easier to read. We also come from the C family of languages where the dominant convention is to write the curly braces on their own line.

We will, however, from this point on be using the same line curly brace convention throughout this tutorial series. The reason is that developers coming from other languages that are learning PHP, mostly come from Javascript (or go to JS afterwards) where the curly brace is written on the same line.

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
<?php

if (true) {
    echo "Main if statement";
    echo "<br>";

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

?>

In the example above we have a secondary conditional within the first.

The interpreter will parse the code hierarchically, meaning that it will evaluate the first if statement, if the condition is true it has permission to go into its execution code block where it will evaluate the next conditional statement.

Even though we are allowed to use nested if statements, it may not always be the correct decision.

A general rule of thumb is that if we are nesting more than 3 levels deep, the code needs to be refactored by using a different approach.

How to write a switch statement

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

As an example, let’s consider that we need to evaluate if a number is between 1 and 10 and for every number, execute different statements. In a normal if grouping it would look like this.

Example:
<?php

$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 correct, it is a lot of typing, especially considering that the evaluation expression only changes slightly each time.

This is where the switch statement comes in handy. Let’s consider the same example but with switch instead of if.

Example:
<?php

$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 and reads clearer, and there is also less typing. On the other side though, the code is less compact.

Let’s consider how to write a switch statement and then break it down step by step.

Syntax:
switch (expression) {
	case expression:
		execution code
		break out of switch
}
Example: switch statement
<?php

$num = 1;

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

?>

Let’s break down the example above.

  1. Firstly, we use the keyword switch .
  2. Next, in between 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 the variable $num , which is 1.
  3. Next, we define scope for the evaluations with open and close curly braces.
  4. Next, we have to define our comparison cases. We do this by writing the keyword case followed by the comparison value and a colon : operator.
    The statement reads: if $num == 1, then do what is after the colon operator .
  5. Following the colon operator, we provide the execution statements. In this case we simply echo the value of the variable $num .
  6. Lastly, we use the break conditional statement to break out of the switch. Essentially, we are telling the compiler that we have found what we are looking for, stop executing the switch and move on to code outside and below it.

We will look at control statements, like break, after loops in the Control StatementsOpens up in a new page tutorial lesson because they are used with both conditional and looping control flow.

Let’s look at another example.

Example:
<?php

$name = "Klaus";

switch ($name) {
    case "Luther":
        echo $name . ": Spaceboy";
        break;
    case "Diego":
        echo $name . ": The Kraken";
        break;
    case "Allison":
        echo $name . ": The Rumor";
        break;
    case "Klaus":
        echo $name . ": The Seance";
        break;
    case "Five":
        echo $name . ": The Boy";
        break;
    case "Ben":
        echo $name . ": The Horror";
        break;
    case "Vanya":
        echo $name . ": The White Violin";
        break;
}

?>

How to write alternative if and switch statements

PHP offers an alternative syntax for some of its control structures like if. This allows PHP to more easily interact with other languages.

To write the alternative syntax, we change the opening curly brace to a colon : and the closing brace to the keyword endif .

If you are familiar with a language like the liquid template language, which is used with a variety of apps including Jekyll and Shopify, this type of syntax will feel familiar to you.

Syntax:
if (expression):
	execution block
endif;
Example: alternative if syntax
<?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; ?>

How to use 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:
<?php

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

?>

In the example above, both the if and else conditions have only one execution statement each.

If this is the case we can write a shorthand version of it with the ternary ? : operator.

We write our expression followed by the question mark symbol ?. Then we specify the execution code if the expression evaluates to true, followed by a colon : and the execution code if the expression evaluates to false.

Syntax:
 expression ? execution_if_true : execution_if_false;
Example: ternary operator
<?php

// Result stored in data container
$result = true ? "True": "False";

// Result used immediately
echo true ? "True": "False";

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

?>

Summary: Points to remember

  • We can control the flow of our application by evaluating conditional expressions, and then executing code based on that.
  • In an if statement, we need a condition to test, and code to execute if that condition evaluates to true.
  • An else statement doesn’t have a condition and cannot be called on its own.
  • We can nest conditional statements inside other conditional statements, although if we nest more than three times, we should try to refactor our code.
  • A switch statement evaluates only one expression.
  • If we only have single execution statements, we can choose not to write the curly braces, or use the ternary operator (? :).