Conditionals
Conditionals alter program flow. They enable you to ask questions about certain things and respond to the answers you get in different ways. Conditionals are central to dynamic web pages—the goal of using PHP in the first place—because they make it easy to create different output each time a page is viewed.
There are three types of nonlooping conditionals: the if
statement, the switch
statement, and the ?
operator. By nonlooping, I mean that the
actions initiated by the statement take place and program flow then
moves on, whereas looping conditionals (which we’ll come to shortly)
execute code over and over until a condition has been met.
The if Statement
One way of thinking about program flow is to imagine it as a single-lane highway that you are driving along. It’s pretty much a straight line, but now and then you encounter various signs telling you where to go.
In the case of an if
statement, you could imagine coming across a detour sign that you have
to follow if a certain condition is TRUE
. If so, you drive off and follow the
detour until you return to where it started and then continue on your
way in your original direction. Or, if the condition isn’t TRUE
, you ignore the detour and carry on
driving (see Figure 4-1).
The contents of the if
condition can be any valid PHP expression, including equality,
comparison, tests for zero and NULL
, and even the values returned by
functions (either built-in functions or ones that you write).
The action to take when an if
condition is TRUE
are generally
placed inside curly braces, { }
.
However, you can ignore the braces if you have only a single statement
to execute. But if you always use curly braces, you’ll avoid having to
hunt down difficult-to-trace bugs, such as when you add an extra line
to a condition and it doesn’t get evaluated due to lack of braces.
(Note that for space and clarity, many of the examples in this book
ignore this suggestion and omit the braces for single
statements.)
In Example 4-19, imagine that it is the end of the month and all your bills have been paid, so you are performing some bank account maintenance.
<?php if ($bank_balance < 100) { $money += 1000; $bank_balance += $money; } ?>
In this example, you are checking your balance to see whether it is less than 100 dollars (or whatever your currency is). If so, you pay yourself 1,000 dollars and then add it to the balance. (If only making money were that simple!)
If the bank balance is 100 dollars or greater, the conditional statements are ignored and program flow skips to the next line (not shown).
In this book, opening curly braces generally start on a new line. Some people like to place the first curly brace to the right of the conditional expression; others start a new line with it. Either of these is fine, because PHP allows you to set out your whitespace characters (spaces, newlines, and tabs) any way you choose. However, you will find your code easier to read and debug if you indent each level of conditionals with a tab.
The else Statement
Sometimes when a conditional is not TRUE
, you may not want to continue on to the
main program code immediately but might wish to do something else
instead. This is where the else
statement comes in. With it, you can set up a second detour on your
highway, as in Figure 4-2.
What happens with an if...else
statement is that the first
conditional statement is executed if the condition is TRUE
. But if it’s FALSE
, the second one is executed. One of
the two choices must be executed. Under no
circumstance can both (or neither) be executed. Example 4-20 shows the use of
the if...else
structure.
<?php if ($bank_balance < 100) { $money += 1000; $bank_balance += $money; } else { $savings += 50; $bank_balance -= 50; } ?>
In this example, having ascertained that you have over $100 in
the bank, the else
statement is
executed, by which you place some of this money into your savings
account.
As with if
statements, if
your else
has only one conditional
statement, you can opt to leave out the curly braces. (Curly braces
are always recommended, though. First, they make the code easier to
understand. Second, they let you easily add more statements to the
branch later.)
The elseif Statement
There are also times when you want a number of different
possibilities to occur, based upon a sequence of conditions. You can
achieve this using the elseif
statement. As you might imagine, it is like an else
statement, except that you place a
further conditional expression prior to the conditional code. In Example 4-21, you can see a
complete if...elseif...else
construct.
<?php if ($bank_balance < 100) { $money += 1000; $bank_balance += $money; } elseif ($bank_balance > 200) { $savings += 100; $bank_balance -= 100; } else { $savings += 50; $bank_balance -= 50; } ?>
In the example, an elseif
statement has been inserted between the if
and else
statements. It checks whether your bank
balance exceeds $200 and, if so, decides that you can afford to save
$100 of it this month.
Although I’m starting to stretch the metaphor a bit too far, you can imagine this as a multiway set of detours (see Figure 4-3).
Note
An else
statement closes
either an if...else
or an
if...elseif...else
statement. You
can leave out a final else
if it
is not required, but you cannot have one before an elseif
; neither can you have an elseif
before an if
statement.
You may have as many elseif
statements as you like. But as the number of elseif
statements increase, you would
probably be better advised to consider a switch
statement if it fits your needs.
We’ll look at that next.
The switch Statement
The switch
statement is
useful in cases in which one variable or the result of an expression
can have multiple values, which should each trigger a different
function.
For example, consider a PHP-driven menu system that passes a
single string to the main menu code according to what the user
requests. Let’s say the options are Home, About, News, Login, and
Links, and we set the variable $page
to one of these, according to the
user’s input.
The code for this written using if...elseif...else
might look like Example 4-22.
<?php if ($page == "Home") echo "You selected Home"; elseif ($page == "About") echo "You selected About"; elseif ($page == "News") echo "You selected News"; elseif ($page == "Login") echo "You selected Login"; elseif ($page == "Links") echo "You selected Links"; ?>
Using a switch
statement, the
code might look like Example 4-23.
<?php switch ($page) { case "Home": echo "You selected Home"; break; case "About": echo "You selected About"; break; case "News": echo "You selected News"; break; case "Login": echo "You selected Login"; break; case "Links": echo "You selected Links"; break; } ?>
As you can see, $page
is
mentioned only once at the start of the switch
statement. Thereafter, the case
command checks for matches. When one
occurs, the matching conditional statement is executed. Of course, in
a real program you would have code here to display or jump to a page,
rather than simply telling the user what was selected.
Note
One thing to note about switch
statements is that you do not use
curly braces inside case
commands. Instead, they commence with a colon and end with the
break
statement. The entire list
of cases in the switch
statement
is enclosed in a set of curly braces, though.
Breaking out
If you wish to break out of the switch
statement because a condition has
been fulfilled, use the break
command. This command tells PHP to break out of the switch
and jump to the following
statement.
If you were to leave out the break
commands in Example 4-23 and the case
of “Home” evaluated to be TRUE
, all five cases would then be
executed. Or if $page
had the
value “News,” then all the case
commands from then on would execute. This is deliberate and allows
for some advanced programming, but generally you should always
remember to issue a break
command
every time a set of case
conditionals has finished executing. In fact, leaving out the
break
statement is a common
error.
Default action
A typical requirement in switch
statements is to fall back on a
default action if none of the case
conditions are met. For example, in
the case of the menu code in Example 4-23,
you could add the code in Example 4-24 immediately
before the final curly brace.
default: echo "Unrecognized selection"; break;
Although a break
command is
not required here because the default is the final substatement, and
program flow will automatically continue to the closing curly brace,
should you decide to place the default
statement higher up it would
definitely need a break
command
to prevent program flow from dropping into the following statements.
Generally the safest practice is to always include the break
command.
Alternative syntax
If you prefer, you may replace the first curly brace in a
switch statement with a single colon, and the final curly brace with
an endswitch
command, as in Example 4-25. However this
approach is not commonly used and is mentioned here only in case you
encounter it in third-party code.
The ? Operator
One way of avoiding the verbosity of if
and else
statements is to use the more compact
ternary operator, ?
, which is
unusual in that it takes three operands rather than the more usual
two.
We briefly came across this in Chapter 3 in the discussion about the
difference between the print
and
echo
statements as an example of an
operator type that works well with print
but not echo
.
The ?
operator is passed an
expression that it must evaluate, along with two statements to
execute: one for when the expression evaluates to TRUE
, the other for when it is FALSE
. Example 4-26 shows code we might use for
writing a warning about the fuel level of a car to its digital
dashboard.
<?php echo $fuel <= 1 ? "Fill tank now" : "There's enough fuel"; ?>
In this statement, if there is one gallon or less of fuel (in
other words $fuel
is set to 1 or
less), the string “Fill tank now” is returned to the preceding
echo
statement. Otherwise, the
string “There’s enough fuel” is returned. You can also assign the
value returned in a ?
statement to
a variable (see Example 4-27).
<?php $enough = $fuel <= 1 ? FALSE : TRUE; ?>
Here $enough
will be assigned
the value TRUE
only when there is
more than a gallon of fuel; otherwise, it is assigned the value
FALSE
.
If you find the ?
operator
confusing, you are free to stick to if
statements, but you should be familiar
with it, because you’ll see it in other people’s code. It can be hard
to read, because it often mixes multiple occurrences of the same
variable. For instance, code such as the following is quite
popular:
$saved = $saved >= $new ? $saved : $new;
If you take it apart carefully, you can figure out what this code does:
$saved = // Set the value of $saved $saved >= $new // Check $saved against $new ? // Yes, comparison is true ... $saved // ... so assign the current value of $saved : // No, comparison is false ... $new; // ... so assign the value of $new
It’s a concise way to keep track of the largest value that
you’ve seen as a program progresses. You save the largest value in
$saved
and compare it to $new
each time you get a new value.
Programmers familiar with the ?
operator find it more convenient than if
statements for such short comparisons.
When not used for writing compact code, it is typically used to make
some decision inline, such as when testing whether a variable is set
before passing it to a function.
Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.