So far we have only looked at very simple programs which run in a linear fashion - one statement after another until the end of the program. To do anything really useful however, you need to create forks in the way PHP scans through your code (this is called control flow). Most often, we do this by inspecting the contents of a variable and executing one segment of code if something is true about it and another segment of code if it's false - this is called a conditional.
The result of a comparison operator is always either TRUE or FALSE (boolean) - it compares one value against another and gives you a result. Here is a list of the comparison operators taken directly from php.net:
| Example | Name | Result |
|---|---|---|
| $a == $b | Equal | TRUE if $a is equal to $b. |
| $a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type. |
| $a != $b | Not equal | TRUE if $a is not equal to $b |
| $a <> $b | Not equal | TRUE if $a is not equal to $b |
| $a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type. |
| $a < $b | Less than | TRUE if $a is less than $b |
| $a > $b | Greater than | TRUE if $a is greater than $b |
| $a <= $b | Less than or equal to | TRUE if $a is less than or equal to $b |
| $a >= $b | Greater than or equal to | TRUE if $b is greater than or equal to $b |
All of the operators can be applied to any two values of any type, although the 'greater than' and 'less than' operators only really make sense when applied to numerical data. You can use conditionals to compare two variables, or a variable and a static value, or two static values (although there's not much point in doing this because the result would never change).
One very important thing to point out here that often trips up beginners is that the double equals equality comparison operator is not the same as the single equals sign assignment operator. A single equals sign makes a variable equal to something, a double equals sign tests whether something is equal to something else without changing it. This is an important difference so make sure you understand it - if you try to do comparisons with a single equals sign you will get unexpected and sometimes hard-to-explain results.
PHP offers two methods to create branches in program flow based on the result of a comparison operator - the most commonly used of these is the 'if' statement, so we'll start with that. It's easier to explain this if we look at an example, so here's a very simple one:
<?php
$name = 'alice';
if ($name == 'alice') {
echo 'Hello Alice';
} else {
echo 'Hello Bob';
}
?>
The first thing we do in this program is assign the value 'alice' to the variable $name. Then we do an equality check on $name to see if it's equal to 'alice' and have two separate blocks of code enclosed in curly brackets - the first to be executed if the condition is TRUE, and the one after the 'else' is executed if the condition is FALSE.
The difference in style of brackets is important - curly brackets have a special function; if you enclose a group of statements within them, they behave as one logical block of code. This is called a compound statement - it means the lines of code are grouped together and behave as one. In place of a compound statement you can always have a single statement instead. For example, the following program is exactly equivalent to the program above:
<?php
$name = 'alice';
if ($name == 'alice')
echo 'Hello Alice';
else
echo 'Hello Bob';
?>
However, using this syntax is discouraged because it can become confusing when you need to add extra lines of code. You will nevertheless probably encounter this syntax in other people's code so it's worth being aware of, otherwise you too will fall victim to the confusion.
The 'else' statement is optional and you can leave it off if you only want to do something if the condition is TRUE. You can also chain 'if' statements together with 'elseif' like this:
<?php
$name = 'alice';
if ($name == 'alice') {
echo 'Hello Alice';
} else if ($name == 'bob') {
echo 'Hello Bob';
} else {
echo 'Hello unknown';
}
?>
You can have as many elseif conditions as you want although if the numbers get huge it's probably time for a slight code redesign just for the sake of readability. Also notice how we increase our level of indentation each time we start a new logical block of code - this is important for readability too because it makes it so much easier to pick out things like missing curly brackets.
Often you will want to make more than one comparison at once and change the flow of code based on more complex decisions than a single check can achieve. This is accomplished via the logical operators. Here's a table of logical operators lifted from php.net:
| Example | Name | Result |
|---|---|---|
| $a and $b | And | TRUE if both $a and $b are TRUE. |
| $a && $b | And | TRUE if both $a and $b are TRUE. |
| $a or $b | Or | TRUE if either $a or $b is TRUE. |
| $a || $b | Or | TRUE if either $a or $b is TRUE. |
| $a xor $b | Xor | TRUE if either $a or $b is TRUE, but not both. |
| ! $a | Not | TRUE if $a is not TRUE. |
The difference between 'and' and '&&' or 'or' and '||' is one of Operator Precedence - Operator precedence basically defines the order in which things are evaluated, and you can alter it by inserting normal round brackets like in mathematics. Here's an example using the logical operators and brackets to change precedence:
<?php
$name = 'alice';
$surname = 'smith';
if ($name == 'alice' && ($surname == 'smith' || $surname == 'jones')) {
echo 'Hello Alice, your surname is either Smith or Jones';
}
?>
If your logical operations get really long it can be helpful to separate them onto multiple lines and use the indenting rule to keep it readable. Most of the time, however, this isn't necessary.
PHP has another way of doing conditionals called the switch statement - this is never required as you can always achieve the same thing with a series of chained together 'if' and 'elseif' statements, however in some cases it can lead to cleaner, easier to read code and you should use every tool in your arsenal to achieve that aim.
Often you will want to check a single variable (or expression) against a bunch of different values - this is what the switch statement is particularly helpful for. Here's an example:
<?php
$name = 'alice';
$surname = 'smith';
if ($name == 'alice') {
switch ($surname) {
case 'smith':
echo 'Hello Alice Smith';
break;
case 'jones':
echo 'Hello Alice Jones';
break;
default:
echo 'Hello Alice unknown';
}
}
?>
If you don't write the break statement, code continues to execute through the rest of the conditions, let's have a look at that as well:
<?php
$name = 'alice';
$surname = 'smith';
if ($name == 'alice') {
switch ($surname) {
case 'smith':
echo 'Hello Alice Smith';
case 'jones':
echo 'Hello Alice Jones and Alice Smith';
break;
default:
echo 'Hello Alice unknown';
}
}
?>
A lot of programmers prefer to avoid switch statements wherever possible because they don't use compound statements like all of the other program flow control constructs. Some say the indenting is less elegant than the equivalent comparisons in an if/elseif block. You'll have to decide for yourself whether you like to use switch or not. The ability to fall through from one condition to the next by omitting the break statement often makes a switch statement the only sensible choice.
You don't need to put a break statement on the end of the last condition because there's nothing for it to fall through to, but it doesn't hurt to get into the habit of putting break statements onto the end of every code block that you write in a switch statement unless you specifically mean to allow code flow to fall through from one condition to the next.
Digital Crocus offer affordable UK web hosting to get you up and running from just $32.49 per year or $3.99 per month. Our most basic account would be enough to get started learning PHP and host a few websites with a moderate amount of traffic. We offer easy upgrade options as your requirement grows and a friendly and helpful email and phone customer support service. If you're looking to buy web hosting, consider giving us a try - under our money back guarantee we'll refund you if you're not 100% satisfied.
Kieran Simkin is an experienced software developer and co-founder of Digital Crocus. Kieran is also a keen amateur photographer and musician and has a personal portfolio which you can see online.