Conditional statements are used in PHP (and in any other programming language) when the programmer wishes to place a branch in the code, where a specific result will occur if, and only if, a set of conditions is matched. A real world example might be
I will go to the cinema if I have $15 or more to spend tonight
if($amount >= 15){ echo "I'm going to the cinema"; }
But, what would you do if you didn’t go to the cinema? There’s usually an alternative…
I will go to the cinema if I have $15 or more. Otherwise, I’ll just stay in and watch TV
This would be represented in PHP as
if($amount >= 15){ echo "I'm going to the cinema"; } else { echo "I'm a bit skint. I think I'll just stay in and watch Friends re-runs again"; }
The first line sets up the proposition, “What’s the value of $amount?” or, “How much money have I got?”. The curly brackets (or braces) are the containers for each of the outcomes (this is an important syntactical feature of PHP).
What we’re saying here is that the echo statement contained within the first pair of braces (line 2) will be executed if the value of $amount is greater than or equal to (>=) 15
The statement within the second set of braces (line 4) is executed when $amount is less than 15. The “else” operator tells PHP that we want one or the other - not both - dependant on the outcome of the “if” statement
PHP, much like any other language, uses the two boolean values TRUE and FALSE to represent the outcome of logical expressions. The result of a statement like “$amount >= 15″ will equal TRUE if the variable $amount holds a numerical value which is greater than, or equal to 15 and FALSE otherwise. Here are some other examples of boolean expressions
5 > 3 //TRUE, 5 is greater than 3 3 < 5 //TRUE, 3 is less than 5 4 >= 4 //TRUE, 4 is indeed greater than or <i>equal to</i> 4 5 != 3 //TRUE, 5 is <i>not equal to (!=)</i> 3 3 != 3 //FALSE, 3 is equal to 3 - the operand "!=" fails here 5 == 5 //TRUE, 5 does indeed equal 5
These are fairly banal examples. I can’t imagine anyone would get excited about writing a program to prove that 5 equals 5!
An important thing to note about the last example is the use of equality operator (==) This is not the same as the assignment operator (=) == is used to check if two values are equal, whereas = is used to assign a specific value to a variable. i.e.
$x = 5; // $x now equals 5 $x == 7; /* 7 doesn't get assigned to $x instead, the whole expression equates to false since $x doesn't equal 7 */
We can see this more clearly by looking at the value of each expression as a whole using var_dump()
var_dump ($x = 5); /* int(5) */ var_dump ($x == 7); /* bool(false) */
Sometimes you want to base the outcome of a situation on more than one variable, you wish to know, for example, that two certain conditions will be fulfilled before deciding on a choice of action. Expanding on our cinema example from earlier -
If I have $15 or more AND it is not raining, I’ll go to the cinema. Otherwise I’ll stay in and watch TV
becomes…
1 2 3 4 5 | if($amount >= 15.00 && !$raining){ echo "I really want to see the new Indiana Jones film"; } else { echo "It's too wet out, and the episode of Friends where they play 'Fireball' is on"; } |
Here, we are using the operator “&&” to represent the expression “and” - similarly, we can use the operator “||” to represent “or”.
This statement is based on two things - firstly, the same condition as before - how much money have I got? Secondly, the condition “!$raining”. The exclamation mark before $raining is means that !$raining will equate to TRUE only if $raining equals FALSE. Confusing? Yes, it is a little bit to begin with, but dealing with logical expressions usually can be!
Think of it this way - it can be rewritten as
if($amount >= 15.00 && $raining == FALSE){
Which makes more sense. You may encounter quite a few situations like this in PHP, where things are written in a specific shorthand that somewhat obscures the meaning, but once you get the hang of it you find it quicker and simpler to use the shorthand version. Take the following code snippet…
Sometimes it might be the case that there aren’t just two potential outcomes to a situation. Indeed, as with most scenarios in life, there are many more. Consider yet another modifcation to the above scenario.
I’m going to the cinema if it’s not raining, and I have $15 or more. If it is raining, I’ll stay in and watch TV. Otherwise, if it isn’t raining, but I have less than $15, I’ll go and visit my friends
Here, we have three unique outcomes - going to the cinema, staying in, or visiting friends. We can work this out with logic by introducing another choice in our if statement, as follows
1 2 3 4 5 6 7 | if($amount >= 15.00 && !$raining){ echo "Let's go to the cinema"; } elseif ($amount < 15.00 && !$raining){ echo "I'm going to visit friends"; } else if($amount < 15.00 && $raining == TRUE) { echo "I think I'll just stay in tonight"; } |
Notice though, in the final case, we’re doing checks for logical conditions that aren’t actually required, given that we can reason, through logical deduction, that if it’s raining, neither of the first cases will match, so the check for $raining == TRUE is redundant. Likewise, because we know that the value of $amount isn’t relevant either, we can safely ignore that too. A more compact way of writing the above code would be
1 2 3 4 5 6 7 | if($amount >= 15.00 && !$raining){ echo "Let's go to the cinema"; } elseif ($amount < 15.00 && !$raining){ echo "I'm going to visit friends"; } else { echo "I think I'll just stay in tonight"; } |
Usually, for the final condition in an if…elseif…else statement, we have already checked for all the relevant conditions we’re interested in, and this final “else” is simply the “default case”
echo ($amount >=15 && !$raining)?"I'm going to the cinema":"I'm going to stay in";
Now what on earth is all that about? Well, it’s exactly the same expression as before - only written in an even more shorthand way. This time, we’re using the conditional operators ? and : to express our situation.
An interesting way to view this is to think of the ? in the statement above in exactly the same way as you would view it in a normal sentence. Let’s reword our thoughts about going to the movies…
Is it dry outside, and do I have more than $15? If so, then I’ll head out. If not, then I’ll stay in
We’re asking a question here - the same question in PHP form reads..
$amount >=15 && !$raining?/* if so */"I'm not going to the cinema":/* otherwise */"I am going to the cinema";
(I added in some extra wording in comments to make it clearer - that might not be fully accepted as valid PHP code though)
Here, we’re using the colon (:) to mean “Otherwise”, so the use of the ? and : operators basically amounts to
(statement which equals either TRUE or FALSE)?Do this if it's true:Do this if it's false;
If you think about it, you can also imagine how you could place other conditional statements within the expressions to be evaluated in either case, to produce even more complex scenarios
Let’s expand again on our cinema example
I’m going to the cinema if it’s not raining, and I have $15 or more. Otherwise I’ll stay in and watch TV. But, if my friends call me up to go along, I’ll head anyway
1 2 3 4 5 | if(($amount >= 15.00 && !$raining) || $friends_have_called == true){ echo "Let's go to the cinema"; } else { echo "Nah, let's not bother"; } |
Here, the conditional statement in line 1 has expanded to include an “or” (||) condition - either, it’s not raining and I have enough money, or, my friends have called. If my friends have called, it doesn’t matter about the first expression.
Note as well, that the first condition has been placed in brackets, instead of writing
1 | if($amount >= 15.00 && !$raining || $friends_have_called == true){ |
Which is prone to misinterpretation (That could be saying “If I have more than $15, and it’s either not raining or my friends have called…”) There is a feature of programming called operator precedence which defines which operator is considered first, but when in doubt, always use brackets to make your statements clearer - it helps when other people look at your code too
One other way of providing a conditional response to an expression is to use the switch() function. This function is especially useful when we expect one of a fixed number of outcomes to occur, and we wish to compare a specific variable to each, to find out which value has occured.
The switch() function also uses the keywords case, default and break, and the exact purpose of these can be seen in the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $i = 2; switch($i){ case 2: echo "i is equal to 2"; break; case 3: echo "i is three"; break; case 1: echo "i is only one here"; break; default: echo "i is neither 1, 2 or 3"; break; } |
The above code will output
i is equal to 2
Here, we are using the case keyword to declare which of the outcomes 1, 2 or 3 we wish to deal with in each case. The switch statement itself is encased within a pair of braces (lines 2 & 15) and each case statement is simply defined by whatever code appears between the colon (:) and the break; statement.
The final case is named “default”, and this is the case which occurs when none of the previous cases is matched. The usage here is similar to the last sentence I wrote in the section above about “elseif” - the last default case is usually the one that requires no extra conditions to be matched.
This switch statement above is identical in functionality to the series of if statements:
1 2 3 4 5 6 7 8 9 10 | $i = 2; if($i==2){ echo "i is equal to 2"; } elseif ($i==3) { echo "i is three"; } elseif ($i==1) { echo "i is only one here"; } else { echo "i is neither 1, 2 or 3"; } |
But the switch statement is arguably more compact, and a bit simpler to code than the equivalent code using “if”
if…else statements can also be written using the following syntax
<?php $result = 0; if($a==1 && $b==2){ echo "Statement 1"; $result = 1; } else if($a==2) { echo "Statement 2"; $result = 2; } else { echo "Statement 3"; $result = 3; } //can be rewritten as... if($a==1 && $b==2): echo "Statement 1"; $result = 1; else if($a==2): echo "Statement 2"; $result = 2; else: echo "Statement 3"; $result = 3; endif; ?>
Note that, in the second code example, there is no need for any braces round each of the results. All the code to be executed based on the logic expression is contained between each of the if:, elseif: and else: statements
Note as well, it’s vitally important to include the “endif;” statement, to replace the final closing brace.
Switch statements can also be written as
switch($i): case 1: echo "one"; break; default: echo "not one"; break; endswitch;
And similar syntactical differences can be applied to while loops, for loops and foreach loops
This way of writing if statements can be useful, and slightly tidier, but is slightly more prone to errors, especially when nesting if statements, and can sometimes produce erratic results




September 19th, 2008 at 5:44 pm
Thanks for this tutorial. I didn’t know about the shorthand conditional operators ? and : . I have seen them before in code but didn’t have a clue what they were. Thanks again!
/k