×
Author:
Website:
Page title:
URL:
Published:
Last revised:
Accessed:

Conditional Statements

Overview

Conditional statements in PHP are used in much the same way as in other programming languages - their purpose is to control the flow of program logic. Consider the following statement:

If it's not raining later, I'm going for a walk.

This is not written in the kind of language you would find in a computer program. It is, nevertheless, a conditional statement. It defines a condition (i.e. that it's not raining later) and an action that will occur if that condition is met (i.e. that I'm going for a walk). It doesn't specify what action will occur otherwise, but we could add a further statement:

If it's not raining later, I'm going for a walk.
Otherwise, I'll stay in and watch television.

We could add even more statements to give ourselves additional alternatives:

If it's not raining later, I'm going for a walk.
Otherwise, if there's anything good on, I'll stay in and watch television.
Otherwise, I'll go to the pub.

Those of you who have done any programming at all will recognise the kind of flow control structures these examples represent in programming terms, namely the if, if...else, and if...elseif...else statements found in virtually all programming languages. PHP provides these, and several other mechanisms, to enable us to control the flow of program execution, including the following:

  • if - execute a block of program instructions if a condition evaluates to TRUE.
  • if...else - execute one of two different blocks of program instructions, depending on whether or not a condition evaluates to TRUE.
  • if...elseif...else - execute one of several different blocks of program instructions, depending on which condition (if any) evaluates to TRUE.
  • switch - execute one of several different blocks of program instructions, depending on which condition (if any) is found to be true. This is essentially the same as if...elsif...else, but can be used for situations where a significant number of possible program states must be considered.
  • match - introduced with PHP 8.0, the match expression is similar to the switch statement in that it has a subject expression that is compared against multiple alternative values. Unlike switch, it returns a value, and carries out its comparisons using the identity operator (===) rather than the equality operator used by the switch statement (==).
  • The ternary operator - this is a special kind of operator that essentially provides a means of writing a simple if...else control structure in a single line of code.

We will be looking at examples of how these control structures are used in some detail in this article, as well as how we can combine various conditional statements to help us implement complex program logic. We will also be looking at an alternative syntax for the if statement and the switch statement which could make life a little easier when writing mixed PHP and HTML code. We'll end the article with some suggestions concerning good coding practice as it relates to implementing program flow control.

The if statement

The if statement is the simplest form of conditional statement. It evaluates some expression to determine whether it evaluates to TRUE, and if so, executes some predefined block of code. It basically says "if expression is true, execute the codeblock". The standard syntax for an if statement is as follows:

if (expression) {
// code to be executed if expression evaluates to TRUE
}

As you can see, the if keyword is followed by the expression to be evaluated enclosed in parentheses, followed by the code to be executed if the conditional expression evaluates to TRUE, enclosed between curly braces. Consider the following example:

<?php
$name = "";
$msg = "Hello stranger.";
if ($name != "") {
$msg = "Hello $name!";
}
echo $msg;
// Hello stranger.
?>

In this example, we have a string variable $name that is set to the empty string (""), and another string variable $msg that is set to "Hello stranger.". The expression within parentheses, $name != "", evaluates to FALSE, so the instructions inside the curly braces are not executed and the $msg variable is not updated. Obviously, the $name variable in this example is hard-coded to be the empty string, but in a real-world script it would typically be updated dynamically by user input.

There are a couple of things to note here. First, the curly braces around the executable code are not strictly necessary in this case because there is only one line of code to be executed. We could, for example, re-write this code as follows:

<?php
$name = "";
$msg = "Hello stranger.";
if ($name != "") $msg = "Hello $name!";
echo $msg;
?>

While this revised code achieves precisely the same end result, and is slightly more compact, it is generally recommended to always include the curly braces because it makes the code more readable. It becomes even more important to use curly braces when we use nested conditional statements (see below), in order to eliminate any ambiguity.

The second thing to note is the position of the curly braces themselves. One widely accepted convention is to position the opening curly brace immediately after, and on the same line as, the conditional expression (the expression in parentheses). The closing curly brace is positioned on its own line following the last line of executable code. That's the convention we tend to use in these pages, but it is not mandatory. We could also do something like this:

<?php
$name = "";
$msg = "Hello stranger.";
if ($name != "")
{
$msg = "Hello $name!";
}
echo $msg;
?>

The only difference here is that the opening curly brace now gets its own line as well. There is nothing wrong with this - the choice of where to put the curly braces is often a matter of personal choice. The important thing is to choose a convention and stick to it (you might also find, if working with other developers on a large project for example, that there are pre-defined coding conventions that you will be asked to conform to).

The conditional expression in parentheses following the if keyword can be any expression that evaluates to a Boolean value (TRUE or FALSE), and the executable code that forms the body of the if statement can consist of any number of program instructions. Note, however, that when the executable code consists of multiple program instructions, curly braces must be used.

The if...else statement

The if...else statement differs from the basic if statement in that it will always execute a block of code, regardless of whether the conditional expression evaluates to TRUE or FALSE, because two alternative blocks of code are defined. If the conditional expression evaluates to TRUE, the first block is executed. If it evaluates to FALSE, the second block is executed. The standard syntax for an if...else statement is as follows:

if (expression) {
// code to be executed if expression evaluates to TRUE
}
else {
// code to be executed if expression evaluates to FALSE
}

The if...else statement basically says "if expression is true, execute the first codeblock, otherwise execute the second codeblock". The else statement essentially defines the default action to be carried out if the conditional expression evaluates to FALSE. Consider the following example:

<?php
if (date("L")) {
echo "It's a Leap Year.";
}
else {
echo "It's not a Leap Year.";
}
// It's not a Leap Year.
?>

In this example we use PHP's Date() function to determine whether or not the current year is a leap year. When used in this way, the Date() function returns 1 if the current year is a leap year, which evaluates to TRUE. Otherwise, it returns 0, which evaluates to FALSE.

The code inside the if statement block will only be executed if the conditional expression evaluates to TRUE, otherwise the code within the else statement will be executed. The else statement has no conditional expression of its own to evaluate. It doesn't need one, because there will only ever be two possible answers to the question being asked here, which is whether or not the current year is a leap year.

The if...else...elseif statement

The if...elsif...else statement differs from both the basic if statement and the if...else statement in that it allows us to define one or more alternative conditional expressions. As with the if...else statement a block of code will always be executed*, but the decision concerning which block of code to execute will depend on which (if any) of the conditional expressions provided evaluates to TRUE. The standard syntax for an if...elseif...else statement is as follows:

if (expression_1) {
// code to be executed if expression1 evaluates to TRUE
}
elseif (expression_2) {
// code to be executed if expression_1 evaluates
// to FALSE and expression_2 evaluates to TRUE
}
.
.
.
elseif (expression_n) {
// code to be executed if all previous conditional
// expressions evaluate to FALSE and expression_n
// evaluates to TRUE
}
else {
// code to be executed if all conditional
// expressions evaluate to FALSE
}

The if...elseif...else statement basically says "Execute the codeblock associated with the first conditional expression found to be true. If none of the conditional expressions are found to be true, execute the last codeblock". As for the if...else statement, the else clause defines the default action to be carried out if none of the conditional expressions supplied evaluate to TRUE. Consider the following example:

<?php
$time = date("H:i");
$hour = substr($time, 0, 2);
if ($hour < 12) {
echo "Good morning! ";
}
elseif ($hour > 16) {
echo "Good evening! ";
}
else {
echo "Good afternoon! ";
}
echo "The time is $time.";
// Good afternoon! The time is 15:49.
?>

In this example we use the Date() function once more, this time to get a string value representing the current time in hours and minutes using the 24 hour format (HH:MM) and assign it to the $time variable. We then use PHP's substr() function to extract the hour, and assign it to the $hour variable.

We are using an if...elseif...else statement here because there are three possibilities. It is either morning, evening, or afternoon. If it is morning ($hour < 12) we will say "Good morning!". If it is evening (i.e. later than 17:00, so $hour > 16), we will say "Good evening!". If neither of these expressions evaluates to TRUE, the $hour variable must have a value in the range 12 - 16, so the time is somewhere between 12:00 and 16:59, and we will say "Good afternoon!"

Once again, the else clause doesn't need a conditional expression of its own because if the other two conditional expressions both evaluate to FALSE, there is only one possibility left - if it is not morning, and it is not evening, then it must be afternoon.

The if...elseif...else statement allows us to handle situations in which there are multiple possible outcomes. The simple example we saw above is based on the premise that the day can divided into three possible phases - morning, evening, and afternoon. A particular time of day can only belong to one of these phases.

It is possible that more than one conditional expression in an if...elseif...else statement evaluates to TRUE. However, the conditional expressions are evaluated in the order in which they appear. Only the block of code associated with the first conditional expression to evaluate to TRUE is executed. Subsequent elseif and else statements are ignored.

One final thing to note is that, in all of the examples we have provided so far, the elseif keyword could be replaced by else if. This will not be the case when we use the alternative syntax for the if..elseif...else statement. We will be looking at the use of the alternative syntax in due course, but this is something you should be aware of. We tend to stick to using elseif, if only because it means we have one less thing to think about when using the alternative syntax.

*If none of the conditional expressions evaluates to TRUE, the code associated with the else clause is executed. Note, however, that it is possible to create an if...elseif statement that has one or more elseif statements but no else statement. In this situation, and if none of the conditional expressions defined for the if or elseif statements evaluate to TRUE, there is no default action, and no code is executed.

The switch statement

Like the if...elseif...else statement, the switch statement allows us to define multiple alternative actions, although it takes a somewhat different approach. A block of code will always be executed*, depending on which (if any) of the case values provided matches the parenthesised expression that follows the switch keyword. The standard syntax for a switch statement is as follows:

switch (expression) {
case value_01:
// code to be executed if expression evaluates to value_01
break;
case value_02:
// code to be executed if expression evaluates to value_02
break;
case value_03:
// code to be executed if expression evaluates to value_03
break;
.
.
.
.
.
.
case value_xx:
// code to be executed if expression evaluates to value_xx
break;
default:
// code to be executed if expression does not match any criteria
}

The switch statement basically says "Execute the codeblock associated with the first case value that matches expression. If no cases match expression, execute the default codeblock, if it exists". Consider the following example:

<?php
$day=date("l");
echo "Today is $day.<br>";
switch ($day)
{
case "Monday":
echo "I hate Mondays!";
break;
case "Tuesday":
echo "The weekend seems a long way off.";
break;
case "Wednesday":
echo "Half way through the week!";
break;
case "Thursday":
echo "One more day before the weekend.";
break;
case "Friday":
echo "Nearly the weekend!";
break;
case "Saturday":
echo "I like Saturdays.";
break;
default:
echo "Sunday is usually a quiet day.";
}
// Today is Friday.
// Nearly the weekend!
?>

The case values in the switch statement are evaluated in order of appearance. Once a case value is found that matches the switch expression, the code associated with that case value is executed. Note that a break statement is necessary in order to prevent the execution of code associated with subsequent case values (an occurrence known as fall-through). The break statement causes program execution to break out of the switch statement body immediately.

Sometimes, you might want the same block of code to be executed for several different case values. In that case, simply list the case values one after the other in the switch statement before the code to be executed for those case values. For example:

<?php
$day=date("l");
echo "Today is $day.<br>";
switch ($day)
{
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "I have to work on $day.";
break;
case "Saturday":
echo "I go shopping on $day.";
break;
default:
echo "$day is a rest day.";
}
// Today is Saturday.
// I go shopping on Saturday.
?>

If no case values are found that match the switch expression, the default code, i.e. the code associated with the default keyword, is executed. No break statement is required after the default code has been executed, because program execution will exit the switch statement automatically at that point.

The default case is the equivalent of the else statement in an if...elseif...else statement, and, like the else statement, it can be omitted. If no case values match the switch expression and there is no default case, the program will exit the switch statement without executing any code.

The match expression

The match expression was introduced in PHP 8.0 and offers similar functionality to the switch statement. The match keyword is followed by a parenthesised expression that is then compared with multiple alternative values until a match is found. The standard syntax for a match expression is as follows:

returnValue = match (expression) {
expr1 => returnValueA,
expr2 => returnValueB,
expr3, expr4, expr5 => returnValueC,
default => returnValueD,
};

There are some significant differences between the match expression and the switch statement. First of all, all comparisons are handled as identity rather than equality checks. In other words, comparison is made on the basis of using the identity operator (===) rather than the equality operator (==). For a value to match the expression provided, it must not only have the same value, but be of the same type.

Unlike the switch statement, a match expression returns a value (although the return value need not be used). As with the switch statement, the body of a match expression is enclosed between curly braces, and consists of a series of statements called arms, each of which lists one or more values for comparison with the expression to be matched, and specifies the value or expression to be returned. Unlike the case values in a switch statement, no break statement is required between arms. Program execution does not fall through from one arm to the next. Consider the following example:

<?php
$day=date("l");
echo "Today is $day.<br>";

$msg = match ($day)
{
"Monday" => "I hate Mondays!",
"Tuesday" => "The weekend seems a long way off.",
"Wednesday" => "Half way through the week!",
"Thursday" => "One more day before the weekend.",
"Friday" => "Nearly the weekend!",
"Saturday" => "I like Saturdays!",
default => "Sunday is usually a quiet day.",
};
echo $msg;
// Today is Saturday.
// I like Saturdays!
?>

This script does exactly the same thing as the first example we used to demonstrate the switch statement, but requires far fewer lines of code. There are some drawbacks to using match expressions, however. The match expression does not require a default arm, but if there is no default arm, and if the expression to be matched is not identical to the values provided for comparison in any of the arms, an error will be thrown.

Unlike a case value in a switch statement, which can be followed by any number of expressions, an arm in a match expression is limited to a single expression, so the match expression cannot be seen as a substitute for the switch statement in every case (no pun intended). There is also the question of readability, because although switch statements are less compact than match expressions and involve more typing, they are also easier to read.

The ternary operator

The ternary operator (?) provides a very concise way of writing if...else statements. It takes three operands: a conditional expression that must evaluate to a Boolean value (TRUE or FALSE), the value or expression to be returned if the comparison evaluates to TRUE, and the value or expression to be returned if the it evaluates to FALSE. The syntax for using the ternary operator is as follows:

$returnVal = condition ? expr1 : expr2;

Like the match expression, the ternary operator returns a value which may be used or ignored. To demonstrate how the ternary operator works, here is the example code we used to demonstrate the if...else statement:

<?php
if (date("L")) {
echo "It's a Leap Year.";
}
else {
echo "It's not a Leap Year.";
}
// It's not a Leap Year.
?>

And here is a script that produces exactly the same outcome using the ternary operator:

<?php
echo date("L") ? "It's a Leap Year." : "It's not a Leap Year.";
// It's not a Leap Year.
?>

The ternary operator makes it possible to replace simple if...else statements with a single line of code. Of course, this only works if the code within the body of both the if and else parts of the if...else statement consists of a single statement, although - unlike the if...else statement - the ternary operator does return a value. If an if...else statement simply allocates values to variables based on the evaluation of a conditional expression, you should consider using the ternary operator instead.

Nested conditional statements

A conditional statement can be nested within another conditional statement. There are many possible combinations involving nested conditional statements, and we're not going to discuss them all here. A typical scenario is one in which we nest one if...else statement inside another. The syntax for this kind of control structure looks like this:

if (expr1) {
// Code to be executed if expr1 is true
if (expr2) {
// Code be executed if expr2 is true
}
else {
// Code be executed if expr2 is false
}
}
else {
// Code be executed if expr1 is false
}

Nested conditional statements allow us to implement complex program logic. However, because the logic embedded within nested conditional statements can be difficult to follow, it is vital to use indentation correctly to increase readability. You should also avoid using multiple levels of nesting. Each additional level of nesting significantly increases the complexity of your code and makes it harder to follow.

The following (admittedly somewhat contrived) example demonstrates how we might use nested if...else statements (we've even thrown in an elseif for good measure!):

<?php
$num = rand(-10,10);
echo "Your randomly chosen number is $num<br>";
if ($num > 0){
echo "The number $num is positive.<br>";
if ($num % 2 === 0){
echo "It is an even number.";
}
else {
echo "It is an odd number.";
}
}
elseif ($num == 0) {
echo "The number $num is neither positive nor negative.<br>";
echo "It is an even number.";
}
else {
echo "The number $num is negative.<br>";
if ($num % 2 === 0){
echo "It is an even number.";
}
else {
echo "It is an odd number.";
}
}
// Your randomly chosen number is -6
// The number -6 is negative.
// It is an even number.
?>

The output from the above script depends on the randomly generated number, which will be in the range -10 to +10. We have shown the output for a randomly selected value of minus six (-6).

Nested conditional statements can be useful but they can also be hard to read. The conventional wisdom is that nesting conditional statements should be avoided if there is another way to achieve the same outcome. For example, we could re-write the above script without nesting conditional statements as follows:

<?php
$num = rand(-10,10);
echo "Your randomly chosen number is $num.<br>";

if ($num > 0) {
echo "The number $num is positive.<br>";
}
elseif ($num == 0) {
echo "The number $num is neither positive nor negative.<br>";
}
else {
echo "The number $num is negative.<br>";
}
if ($num % 2 === 0) {
echo "It is an even number.";
}
else {
echo "It is an odd number.";
}
// Your randomly chosen number is 8.
// The number 8 is positive.
// It is an even number.
?>

Alternative syntax

From version 4.0 onwards, PHP has provided an alternative syntax for the if family of conditional statements (if, if...else and if...elseif...else) and the switch statement. In every case, the opening curly brace is replaced by a colon (:), and the closing curly brace is replaced by endif (for if statements) or endswitch (for switch statements). Here is the alternative syntax for the if statement:

if (expression):
// code to be executed if expression evaluates to TRUE
endif;

We could thus rewrite the example we gave earlier using the alternative syntax as follows:

<?php
$name = "";
$msg = "Hello stranger.";
if ($name != ""):
$msg = "Hello $name!";
endif;
echo $msg;
// Hello stranger.
?>

The alternative syntax can also be used for conditional statements that feature the else and elseif clauses. Here is the example we saw earlier, re-written using the alternative syntax:

<?php
$time = date("H:i");
$hour = substr($time, 0, 2);
if ($hour < 12):
echo "Good morning! ";
elseif ($hour > 16):
echo "Good evening! ";
else:
echo "Good afternoon! ";
endif;
echo "The time is $time.";
// Good afternoon! The time is 15:49.
?>

And here is the revised version of our first switch statement example:

<?php
$day=date("l");
echo "Today is $day.<br>";
switch ($day):
case "Monday":
echo "I hate Mondays!";
break;
case "Tuesday":
echo "The weekend seems a long way off.";
break;
case "Wednesday":
echo "Half way through the week!";
break;
case "Thursday":
echo "One more day before the weekend.";
break;
case "Friday":
echo "Nearly the weekend!";
break;
case "Saturday":
echo "I like Saturdays.";
break;
default:
echo "Sunday is usually a quiet day.";
endswitch;
// Today is Monday.
// I hate Mondays!
?>

The choice of whether or not to use the alternative syntax for conditional statements is, to some extent, a matter of personal choice, although there are good arguments for using it in certain situations. It can make the code somewhat easier to read when there are long blocks of code inside the if, elseif and else clauses of an if...elseif...else statement, for example, or when a loop construct using curly braces is nested within a conditional statement. It can also make life somewhat easier if you are writing a lot of mixed PHP and HTML code - something we will be exploring in more detail elsewhere.

Note that nesting a conditional statement that use the curly brace syntax inside one that uses the alternative syntax is considered bad practice and can lead to unexpected results. Choose one or the other, and avoid mixing the two.

One final thing to note, as we mentioned previously, is that PHP does not distinguish between the elseif and else if keywords when the traditional curly brace syntax is used with conditional statements. This is not the case when we use the alternative syntax, and using else if will generate a parse error. We therefore recommend using the elseif keyword exclusively to avoid any potential problems.

Best practice

  • Use appropriate and consistent indentation with conditional statements to make your code as easy to read as possible. This is even more important if you are using nested conditional statements.
  • The positioning of curly braces in conditional statements is often a matter of personal preference, but choose a convention and use it consistently.
  • Provide break statements at the end of each case clause in your switch statements to prevent fall-through, and provide a default clause to handle conditions not matched by any of the case values.
  • If using nested conditional statements, avoid using more than three levels of nesting as this can render your code unmanageable. If possible, avoid nesting conditional statements altogether.
  • Use concise but meaningful variable names in order to make your code more readable. That goes for writing code in general, not just in conditional statements, but it is even more important to be able to recognise and identify the purpose of a variable when creating complex flow control structures.
  • Unless using PHP's alternative syntax, always use curly braces, even if the code between them consists of only a single program statement, because it makes the code more readable. This is even more important when using nested conditional statements.
  • Test your code to ensure that it works as expected under all possible conditions (this is known as edge case testing and involves testing your code to ensure that it can handle the complete range of possible inputs).