- Getting Started
- Control Structures and Operators
- Data Types and Functions
- Building Functions
- Exception Handling
- Working with Files
- Variables and Scope
- Building Packages
- Working with Forms
- Debugging PHP
- Summary
3.2 Control Structures and Operators
Usually programs need so-called control structures, which are used to decide at runtime what a program has to do. Flow control is an important part of every programming language and is essential for building applications. PHP provides a broad range of methods, as you will see in this section.
3.2.1 Operator and IF/ELSE/ELSEIF Statements
Use if to check whether a certain expression is true or not. If is supported by all commonly used programming languages such as C/C++, Java, Perl, and Python, and therefore it is a fundamental instrument of every computer programmer. To show you how conditions can be checked using if, we include a short example:
<?php if (2 > 1) { echo '2 is higher than 1<br>'; } ?>
A message will be displayed on the screen because 2 is higher than 1. If the condition wasn't fulfilled, nothing would be displayed.
NOTE
If an empty document is returned by PHP, an error will be raised by some browsers.
Normally if is used to decide whether or not something has to be done. If a certain condition is fulfilled, PHP will execute the code in parentheses, but what has to be done if a condition is not fulfilled? If is very often used in combination with else. Every time an expression in the if statement returns false, the code of the else branch will be executed. Using if in combination with else is an extremely comfortable feature because it makes programming much easier and helps you to avoid bugs. In the next example you will learn how to use if and else:
<?php $a=23; $b=34; if ($a > $b) { echo 'a is higher than b'; } else { echo 'b is higher than a'; } ?>
First, we initialize two variables. $a is set to 23 and 34 is assigned to $b. In the next step we check if $a is higher than $b. If the expression returns true, a is higher than b will be displayed on the screen. Otherwise, b is higher than a will be the result of the program.
In the next example you will see what you can do if you want a message to be displayed if $b is higher than $a and $b is higher than 30:
<?php $a=23; $b=34; if ($a > $b) { echo 'a is higher than b'; } else { if ($b > 30) { echo 'b is higher than a and higher than 30.'; } } ?>
$a is lower than $b, so PHP will execute the else branch. In the else branch you use a second if statement to find out if $b is higher than 30. It is an easy task to solve the problem the way it is shown in the previous example, but it is not the most elegant way:
<?php $a=23; $b=34; if ($a > $b) { echo 'a is higher than b'; } elseif ($b > 30) { echo 'b is higher than a and higher than 30.'; } ?>
Instead of using a second if statement in the else branch, it is also possible to use elseif, which is in most cases the shorter and more elegant way.
Sometimes it is necessary to find out if two or more conditions are fulfilled. Therefore multiple expressions can be combined using operators and parentheses. Assume that you want to check whether $a is higher than 10 but lower than 50:
<?php $a=23; if ($a > 10 && $a < 50) { echo "$a higher than 10 and lower than 50"; } ?>
You can use the && operator to tell PHP that both conditions have to be fulfilled; otherwise, false will be returned and the else branch, which does not exist in our example, will be executed. && is equal to and, so it does not matter if we use ($a > 10 and $a < 50) or ($a > 10 && $a < 50) in our example. Using && instead of and is the more common way because && is also supported by programming languages like C/C++ and Perl. If you execute the example, the result will be 23 higher than 10 and lower than 50.
The counterpart of and is the or operator. If or is used, true will be returned if one expression returns true. Let's have a look at an example:
<?php $a=2; if ($a > 10 || $a < 50) { echo "$a higher than 10 or lower than 50"; } ?>
You want a string to be printed on the screen if $a is either higher than 10 or lower than 50. If one of those conditions is fulfilled, the string will be displayed. The number 2 is not higher than 10 but lower than 50, so we can find 2 higher than 10 or lower than 50 printed on the screen. Instead of || you can also use or.
Another important operator is the xor operator. False is returned if both values are the same; otherwise, the result is true. The next example demonstrates the usage of xor.
<?php $a=18; $b=19; if ($a xor $b) { echo '$a and $b are the same'; } else { echo '$a and $b are not the same'; } ?>
As you might have expected, $a and $b are not the same is returned by the script.
So far, you have learned to use &&, ||, and xor. Now it is time to use these operators as a team to build more complex expressions. Assume that you want a string to be displayed if $a is higher than 10 and lower than 20 or exactly 2. In this case it is necessary to group expressions:
<?php $a=2; if (($a > 10 && $a < 20) || $a == 2) { echo "$a higher than 10 but lower than 20 or exactly 2"; } ?>
The first expression consists of two parts, which are connected using &&. If all expressions in parentheses are fulfilled, the first part will return true. If either the first or the second part of the entire expression returns true, the result will be true. In your case the second part of the expression is an exact match, so the entire expression is true.
Those among you who haven't done a lot of computer programming yet might wonder why == is used instead of = in the example you have just seen. It is not a typo. == is used to check whether two variables are the same. =, however, is used to find out whether a variable can be assigned to another variable. Let's have a look at a very simple example:
<?php $a=18; if ($a = $b) { echo '$a can be assigned to $b'; } else { echo '$a cannot be assigned to $b'; } ?>
First, a value is assigned to $a. In the next step you try to find out if $b can be assigned to $a. Therefore you have to use the = operator. Because $b hasn't been used yet, the else branch will be executed.
If statements can also be used to find out whether a variable has already been defined. As you will see in the section called "Working with Forms," later in this chapter, checking variables is essential for every PHP program. The next example shows how you can find out whether a variable has already been in use:
<?php if ($a) { echo '$a has already been defined'; } else { echo '$a has not been defined yet'; } ?>
In this case the result will be $a has not been defined yet because $a has not been used before.
3.2.2 WHILE and DO..WHILE
WHILE loops are very widespread in programming languages. Like almost all other programming languages, PHP provides WHILE loops, but what are WHILE loops good for? WHILE loops are used to execute a piece of code multiple times. Here is an example of a simple WHILE loop:
<?php echo '<html><body>'; $a=1; while ($a <= 5) { echo "a: $a<br>\n"; $a++; } echo '</body></html>'; ?>
The numbers from one to five are displayed. First, some HTML code is generated. In the next step we set $a to 1 and start the loop. The code between the curly brackets has to be executed until $a is higher than 5. Every time the loop is processed, a: and the content of $a are displayed on the screen. After that $a is incremented by one. The ++ operator is very often used in languages like C and C++. As you can see, it is also available in PHP. $a++ is equal to $a=$a+1.
Let's have a look at what is displayed in the browser when we execute the script:
a: 1 a: 2 a: 3 a: 4 a: 5
As we have promised, the numbers from 1 to 5 are displayed. The HTML code you generated will not be displayed on the screen because it is used only by the browser.
The syntax that has just been described is the most commonly used way of using WHILE loops. However, PHP provides an additional way of using WHILE:
<?php echo '<html><body>'; $a=1; while ($a <= 5): echo "a: $a<br>\n"; $a++; endwhile; echo '</body></html>'; ?>
The code shown in the preceding listing is equal to the code you have seen before. The only difference is the way WHILE is used. In the second example you don't use curly brackets, so you have to tell PHP when the loop ends. This is done using endwhile.
If you are using loops, make sure that the condition that makes the loop stop will be false after executing the loop for the desired number of times; otherwise, the loop will run until one of the components (PHP, the kernel, the Web server, and so forth) stops the execution of the script. In your case you'd have an endless loop if $a was never incremented. Endless loops are very dangerous and you have to keep that in mind. PHP offers an option in php.ini to limit both the memory consumption and runtime of a PHP script. We highly recommend setting these options to a reasonable value.
Sometimes it is necessary to execute the code of a loop once and to check the condition for stopping the loop after that. For that PHP offers do..while loops:
<?php echo '<html><body>'; $a=6; do { echo "a: $a<br>\n"; } while ($a <= 5); echo '</body></html>'; ?>
First, 6 is assigned to $a, and then we start the loop using do. $a, which is 6, is displayed on the screen and you check if the loop has to be executed again. Because 6 is higher than 5, the echo command won't be executed again. In this case you are lucky because if $a was lower than 6, you'd run into an infinite loop. $a is not increased, so ($a <= 5) would always be true.
What can you do if you have to leave a loop in the middle of a block? PHP has the right solution for you. Break is a command that can be used to stop all kinds of loops in the middle of a block. Here is an example:
<?php echo '<html><body>'; $a=1; do { echo "a: $a<br>\n"; $a++; if ($a == 3) { break; } } while ($a <= 5); echo '</body></html>'; ?>
You want to execute the loop as long as $a is lower than 6, but if $a is equal to 3, you want to exit the while loop.
If you execute the script, you can see the result in the browser:
a: 1 a: 2
Two lines will be displayed because the loop is interrupted after printing two lines on the screen.
Continue is another important keyword when dealing with loops. Continue is used to stop the execution of a block without leaving the loop. The idea is to ignore steps in the loop. Here is an example:
<?php echo '<html><body>'; $counter=0; $test=10; while ($counter < $test) { if ($counter %2) { $counter++; continue; } echo "Current value of counter: $counter<br>"; $counter++; } echo '</body></html>'; ?>
The loop is executed until $counter is equal to $test. In the loop you try to find out if $counter can be divided by two. If the result is different from 0 (in your case if it is 1), increment the counter and use continue. The program will start to check the condition again and if it is still true, the block will be executed again.
The output of the script is not surprising:
Current value of counter: 0 Current value of counter: 2 Current value of counter: 4 Current value of counter: 6 Current value of counter: 8
One line is generated for every second number the loop is processed for.
Continue can also be used to leave more than just one loop. Let's have a look at the next example:
<?php echo '<html><body>'; $counter=0; while ($counter == 0) { $counter++; $inner=0; while ($inner == 0) { $inner++; continue 2; echo "inner<br>"; } echo "middle<br>"; } echo "outer<br>"; echo '</body></html>'; ?>
You can see two while loops. Every loop is entered, but in the inner loop you call continue with a parameter to tell PHP how many loops have to be left. In this case you tell PHP to leave two loops, so the result is outer. Nothing else is displayed on the screen. Very efficient applications can be built by using continue with parameters, but this is also very dangerous because a programmer can easily lose the overview of the logic flow of the source code.
3.2.3 FOR
If a block has to be executed a fixed number of times, it is recommended to use for loops instead of while loops.
A for loop consists of a starting value, a condition that is checked every time the loop is processed, and an expression that is executed after every time the loop is processed. Let's have a look at an example:
<?php echo '<html><body>'; for($i = 0; $i < 5; $i++) { echo "i: $i<br>\n"; } echo '</body></html>'; ?>
You want to display the numbers from 0 to 4 on the screen. Therefore a for loop has been implemented in the script. The loop starts with $i being 0 and it is executed as long as $i is lower than 5. The third parameter tells PHP to increment $i after every time the loop is processed. The output of the script shows what comes out when you start the program using a Web browser.
i: 0 i: 1 i: 2 i: 3 i: 4
Sometimes it is necessary to implement more powerful and more complex for loops. Just as in many other languages like C or C++, a list of conditions can be used in combination with for loops. This feature is very important because it allows you to implement complex features with little effort:
<?php echo '<html><body>'; for($i = 0, $j = 10; $i < 5, $j > 0; $i++, $j = $j - 2) { echo "i: $i --- j: $j<br>\n"; } echo '</body></html>'; ?>
All three parameters consist of a list of expressions used to process a certain variable. The text generated by the program shows what has happened to the variables in the program:
i: 0 --- j: 10 i: 1 --- j: 8 i: 2 --- j: 6 i: 3 --- j: 4 i: 4 --- j: 2
$i was incremented by one, whereas $j was reduced by two every time the loop was processed. Using the syntax you have just seen allows you to treat multiple variables using just one for loop. The list of operations used in the loop can easily be extended to the desired complexity.
Up to now, you have learned to use for loops with a list of expressions. However, in PHP, programmers are not forced to provide a list of at least one parameter because it is also possible to leave the list empty, as shown in the following example:
<?php echo '<html><body>'; $i=0; for (; $i < 5; ) { echo "i: $i<br>\n"; $i++; } echo '</body></html>'; ?>
The first and the third parameter of the for loop are empty. The result of the loop is still a list of all numbers from 0 to 4, but it has been generated differently. $i is initialized in the line before the loop starts and it is incremented after displaying the output on the screen:
i: 0 i: 1 i: 2 i: 3 i: 4
As you can see, there are many ways to solve the problem because PHP has a comparatively rich syntax. For those of you out there who are interested in writing very short and efficient code, the next example might be of interest:
<?php echo '<html><body>'; for ($i = 0; $i < 5; print "i: $i<br>", $i++); echo '</body></html>'; ?>
The output of the script is still the same, but we needed only one line to print the numbers on the screen. As you can see, PHP allows you to use any kind of expressions in a for loop, which makes that kind of loop extremely flexible.
3.2.4 SWITCH
To avoid long sequences of if statements, it is sometimes possible to use switch and case statements instead. Switch and case are often used to find the right piece of code that has to be executed from a list of possibilities. Let's have a look at the next example:
<?php $a=2; switch ($a) { case 1: echo "case 1: \$a is $a<br>"; break; case 2: echo "case 2: \$a is $a<br>"; break; case 3: echo "case 3: \$a is $a<br>"; break; } ?>
First, 2 is assigned to $a. The switch statement checks all cases and if the right value is found, the branch is entered and PHP executes all the code until a break command is found. If you execute the script, one line will be displayed:
case 2: $a is 2
The same result can also be achieved by using if statements instead of switch and case:
<?php $a=2; if ($a == 1) { echo "case 1: \$a is $a<br>"; } if ($a == 2) { echo "case 2: \$a is $a<br>"; } if ($a == 3) { echo "case 3: \$a is $a<br>"; } ?>
You can print the string $a on the screen. The $ character has to be escaped using a backslash because otherwise PHP would display the content of the variable $a instead of the string $a on the screen.
In the next step you will try to use switch and case without using break as well:
<?php $a=2; switch ($a) { case 1: echo "case 1: \$a is $a<br>"; case 2: echo "case 2: \$a is $a<br>"; case 3: echo "case 3: \$a is $a<br>"; } ?>
The result of the version using no break commands differs significantly, as you can see in the following example:
case 2: $a is 2 case 3: $a is 2
All of a sudden two lines are returned and that is definitely not the result you want. PHP searches for the right value and executes the code until a break command is found. In your case no break commands are in the code, so it is executed until the end. In some cases this might be the desired behavior of the program, but in most cases it is not.
Another feature of switch and case is the ability to handle default values. If no value in the list matches, PHP will execute the default branch. In the following example, you are looking for 9, but 9 is not listed in the switch statement:
<?php $a=9; switch ($a) { case 1: echo "case 1: \$a is $a<br>"; break; case 2: echo "case 2: \$a is $a<br>"; break; default: echo "the value couldn't be found<br>"; } ?>
PHP will execute the default code because 9 has not been found in the list:
the value couldn't be found
As we have already mentioned, you can make a workaround using if statements instead of switch and case, but this can be far more complex especially when default values are involved and some of your branches do not contain break statements. Let's have a look at the next example. The target is to display 1 and 2 on the screen if the switch statement is called with $a being 1. In all other cases, only the value switch is called with should be displayed:
<?php $a=1; switch ($a) { case 1: echo '1<br>'; case 2: echo '2<br>'; break; case 3: echo '3<br>'; break; default: echo 'default'; } ?>
The task is easy because the only thing you have to do is to write a switch block where every entry but the first one contains a break command.
Switch and case constructions are a very flexible and powerful feature of PHP. It is possible to build sophisticated applications without having to use complex if/else constructs.