Learn PHP in One Day and Learn It Well

PHP for Beginners with Hands-on Project. The only book you need to start coding in PHP immediately. By Jamie Chan

Chapter 6: Control Structures in PHP

Congratulations on making it to Chapter 6; this is where the fun begins!

In this chapter, we are going to look at various control structures in PHP, such as the if statement, for loop and while loop. These structures allow us to control the flow of our programs.

However, before we do that, we need to discuss two sets of operators – the comparison and logical operators. Controlling the flow of our programs involves evaluating the results of these operators and proceeding accordingly.

6.1 Comparison operators

Let’s look at comparison operators first. These operators compare two values and return true or false based on the result of the comparison. They include:

Equal ( == )

Returns true if the values on both sides are equal
(e.g., 5 == 5'Hello' == 'Hello' and 5 == 5.0 all return true )

Identical ( === )

Returns true if the values on both sides are equal and of the same date type (e.g., 5 === 5 returns true while 5 === 5.0 returns false )

Not equal ( != or <> )

Returns true if the values on both sides are not equal(e.g., 5 != 7 and 5 <> 7 both return true )

Not identical ( !== )

Returns true if the values on both sides are not equal or not of the same data type(e.g., 5 !== 5.0 returns true as 5 and 5.0 are of different data types)

Greater than ( > )

Returns true if the value on the left is greater than the value on the right (e.g., 7 > 2 returns true )

Greater than or equal to ( >= )

Returns true if the value on the left is greater than or equal to the value on the right (e.g., 8 >= 5 and 6 >= 6 both return true )

Less than ( < )

Returns true if the value on the left is less than the value on the right (e.g., 9 < 12 returns true )

Less than or equal to ( <= )

Returns true if the value on the left is less than or equal to the value on the right (e.g., 10 <= 14 and 13 <= 13 both return true )

Spaceship (<=>)

Introduced in PHP 7.

Returns 0 if the values on both sides are equal (not necessarily identical)

Returns 1 if the value on the left is greater

Returns -1 if the value on the left is smaller (e.g., 5 <=> 7 returns -1 while 5 <=> 5.0 returns 0 )

6.2 Logical Operators

Next, we have the set of logical operators. The commonly used ones include:

NOT

The NOT ( ! ) operator returns true when it precedes an expression that is false .

For instance, !(5 > 10) returns true as 5 > 10 is false (i.e., 5 is not greater than 10).

AND

The AND operator allows us to combine two comparisons and returns true when both comparisons return true . We can use either the and keyword (case-insensitive) or the && symbol. The two are similar but have different precedence.

Let’s look at some examples:

Example 1:

$a = 5 > 3 and 4 < 10;
$b = 5 > 3 && 4 < 10;
$c = 5 > 1 && 13 < 5;
var_dump($a);
var_dump($b);
var_dump($c);

Output:

bool(true) bool(true) bool(false)

In the example above, $a and $b are true as both comparisons ( 5 > 3 and 4 < 10 ) are true . In contrast, $c is false as the second comparison ( 13 < 5 ) is false .

Example 2:

$d = 3 > 2 && 3 < 1;
$e = 3 > 2 and 3 < 1;
var_dump($d);var_dump($e);

Output:

bool(false) bool(true)

This example illustrates the difference in precedence between the and keyword and the && symbol.

 && has higher precedence than the assignment ( = ) operator. Hence, the statement

$d = 3 > 2 && 3 < 1;

is evaluated as

$d = (3 > 2 && 3 < 1);

 $d is false as 3 < 1 is false .

In contrast, the and keyword has lower precedence than the assignment operator. Hence, the statement

$e = 3 > 2 and 3 < 1;

is evaluated as

($e = 3 > 2) and 3 < 1;

 $e is true as only the result of the first comparison ( 3 > 2 ) is assigned to it.

In most cases, using && is preferred due to its higher precedence.

OR

Next, we have the OR operator. This operator returns true when at least one comparison returns true . We can use either the or keyword or the || symbol. However, I encourage you to use || as it has higher precedence.

Example

$f = 4 < 7 || 10 > 3;
$g = 3 < 2 || 3 > 1;
$h = 10 > 15 || 12 < 1;
var_dump($f);
var_dump($g);
var_dump($h);

Output

bool(true) bool(true) bool(false)

 $f is true as both comparisons are true .

 $g is true even though the first comparison ( 3 < 2 ) is false . This is because || only requires at least one comparison to be true .

 $h is false as none of the comparisons are true .

6.3 Control Structures

Now that we are familiar with comparisons, we are ready to discuss the various control structures in PHP.

6.3.1 If Statement

The first is the if statement. This statement allows the program to evaluate if a certain condition is met and perform an appropriate action based on the result of the evaluation.

The syntax of an if statement is as follows:

if (condition 1 is met){
	//Do task A
}
elseif (condition 2 is met){
	//Do task B
}
elseif (condition 3 is met){
	//Do task C
}
else{
	//Do task D
}

Let’s look at an actual example (line numbers are added for reference and are not part of the actual code).

1 $a = 7;
2
3 if ($a < 0)
4 {
5 	echo 'if block<BR>';
6 	echo '$a is smaller than 0';
7 }
8 elseif ($a < 5)
9 	echo 'First elseif block';
10 elseif ($a < 10)
11	echo 'Second elseif block';
12 else
13 	echo 'Else block';

Here, we first declare a variable called $a and assign the value 7 to it.

Next, from lines 3 to 7, we have the if block.

This block tests if the condition $a < 0 (on line 3) is true . If it is, the program executes everything inside the pair of curly braces that follows (i.e., lines 4 to 7), skipping the rest of the if statement (from lines 8 to 13).

On the other hand, if $a < 0 is not true, the program skips lines 4 to 7 and moves on to test the first elseif condition ( $a < 5 ) on line 8.

If this condition is true , it executes the statement on line 9, skipping the rest of the if statement. Notice that we did not enclose line 9 in curly braces? This is because curly braces are optional if there is only one statement to execute.

If the condition $a < 5 is not true, the program moves on to test the next elseif condition ( $a < 10 ) on line 10. If this condition is also not true, it proceeds to the else block and executes line 13.

There can be as many elseif blocks as you want in an if statement. We have two elseif blocks in the example above.

In addition, elseif and else blocks are optional. If we omit them, the if statement will just do nothing if the if condition is not met. If you run the code above, you’ll get the following output:

Second elseif block

As $a equals 7 , it fails the if condition ( $a < 0 ) and the first elseif condition ( $a < 5 ). However, it passes the second elseif condition ( $a < 10 ). Hence, line 11 is executed. Try changing $a to other values on line 1 and rerun the code to fully appreciate how it works. The output for some possible values of $a is shown below:

If $a equals -2 , we’ll get

if block
$a is smaller than 0

If it equals 3 , we’ll get

First elseif block

If it equals 11 , we’ll get

Else block

6.3.2 Ternary Operator

Next, let’s move on to talk about the ternary operator. In the previous example, we have a relatively complex if statement with two elseif blocks.

If you only want to do a simple if-else test (without any elseif blocks), you can use the ternary operator ( ? ). The syntax is as follows:

Condition ? Task A : Task B

The ternary operator first checks the condition on its left. If it is true , it performs task A. Else, it performs task B.

Let’s look at an example:

$a = (7 == 7 ? 'Yes' : 'No');
echo $a;

Here, the condition to test is 7 == 7 .

As this condition is true , the ternary operator performs the first task and returns the string 'Yes' . We then assign this string to $a and use the echo statement to display its value on the next line.

If we run the code above, we’ll get “Yes” as the output. In contrast, if we change the ternary statement to

$a = (7 > 10 ? 'Yes' : 'No');

we’ll get “No” as the output as 7 > 10 is false .

6.3.3 Switch Statement

Next, we have the switch statement. This statement is similar to an if statement and can be faster if you have many conditions to test. It is typically used when the condition involves comparing a variable against a single value (instead of a range of values).

The syntax is as follows:

switch (variable used for switching) {
	case firstCase:
 	  Task A;
 	  break;
	case secondCase:
	  Task B;
	  break;
...
	default:
	  Default task;
}

Let’s look at an example (line numbers are added for reference):

1 $b = 20;
2
3 switch ($b)
4 {
5 	case 10:
6 		echo 'Chocolate<BR>';
7 		break;
8 	case 20:
9 		echo 'Lemon<BR>';
10 	case 25:
11 		echo 'Strawberry<BR>';
12 		break;
13 	default:
14 		echo 'None of the above<BR>';
15 }

In the example above, we first declare a variable called $b and assign 20 to it.

Next, we have a switch statement from lines 3 to 15.

On line 3, the switch statement uses the value of $b to decide which case to execute. When a certain case is satisfied, everything starting from the next line is executed until a break statement is reached.

If $b is 10 , case 10 is satisfied. The program executes everything after line 5 until it reaches the break statement on line 7. In other words, it executes line 6 and gives us “Chocolate” as output.

On the other hand, if $b is 20 , case 20 is satisfied. However, this case does not have a break statement. Hence, the program executes everything starting from line 9, until it reaches a break statement on line 12. In other words, it executes cases 20 and 25 and gives us “Lemon”, followed by “Strawberry” as output.

Next, if $b is 25 , case 25 is satisfied. The program executes line 11 and gives us “Strawberry” as output.

Finally, if $b is not 1020 or 25 , the default case is executed and we’ll get “None of the above” as output.

The default case is optional. In addition, we can have as many cases as we want in a switch statement. In our example, we have three cases.

If you run the switch statement above, you’ll get

Lemon
Strawberry

as output. Try changing $b to other values on line 1 and run the code again to fully appreciate how the switch statement works.

6.3.4 For Loop

Next, let’s move on to the for loop. This control structure executes a block of code repeatedly until the test condition is no longer valid.

The syntax is as follows:

for (initial value; test condition; modification to value){
  //Do Some Task
}

Let’s look at an example:

for ($c = 1; $c < 5; ++$c){
	echo 'The value of $c is '.$c.'<BR>';
}

The main focus of a for loop is the first line. There are three parts to this line, each separated by a semicolon. In our example, we have the line

for ($c = 1; $c < 5; ++$c)

The first part declares a variable $c and initializes it to 1 .

The second part tests if $c is smaller than 5 . If it is, the statement(s) inside the curly braces that follow will be executed. In our example, the curly braces are optional as there is only one statement to execute.

After executing the statement(s) in the curly braces, the program returns to the third part ( ++$c ). This part modifies the value of the variable used for testing. In our example, we increase the value of $c by 1 using the increment operator. As a result, $c becomes 2 .

After the increment, the program tests if the new value of $c is still smaller than 5. If it is, it executes the code in the curly braces again.

This process of testing and updating the value of $c is repeated until the condition $c < 5 is no longer true. At this point, the program exits the for loop and continues to execute other statements after the for loop.

If you run the code above, you’ll get

The value of $c is 1
The value of $c is 2
The value of $c is 3
The value of $c is 4

as the output.

6.3.5 Foreach Loop

Next, we have the foreach loop. This loop is similar to the for loop but is used to loop over arrays. There are two syntaxes:

foreach ($array as $value) {
	//code to be executed;
}
foreach ($array as $key=>$value) {
	//code to be executed;
}

The names $array$value and $key in the syntaxes above are chosen by us; we can use other names if we want.

Let’s look at an example. This example uses the first syntax:

$arr1 = array(11, 12, 13, 14, 15);
foreach ($arr1 as $num){
	echo 'The number is '.$num.'<BR>';
}

Here, we declare an array called $arr1 with values 11121314 and 15 .

Next, we have the foreach loop. This loop loops through the elements in $arr1 one by one and assigns each element to a variable called $num .

The first time the loop runs, the first element in $arr1 is assigned to $num . In other words, 11 is assigned to $num .

After assigning 11 to $num , the program executes the code in the pair of curly braces that follows. This gives us “The number is 11” as the output.

Once that is done, the foreach loop moves on to the second element and assigns it to $num .

 $num becomes 12 and the echo statement is executed again to give us “The number is 12” as output.

This keeps repeating until all the elements in $arr1 have been accounted for. If you run the code above, you’ll get

The number is 11
The number is 12
The number is 13
The number is 14
The number is 15

as the output.

Next, let’s look at a foreach loop that uses the second syntax. This syntax gives us both the values and keys of the elements in an array and is very useful when working with associative arrays. Suppose we have

$arr2 = array('Aaron'=>12, 'Ben'=>23, 'Carol'=>35);

To get the keys and values of the elements in $arr2 , we can use the foreach loop below:

foreach ($arr2 as $name=>$age){
	echo $name.' is '.$age.' years old.<BR>';
}

This gives us

Aaron is 12 years old.
Ben is 23 years old.
Carol is 35 years old.

as the output.

6.3.6 While Loop

Next up is the while loop. This loop performs a task repeatedly while a specific condition remains valid. The syntax is as follows:

while (condition is true){
	//do A 
}

As usual, let’s look at an example:

1 $d = 1;
2
3 while ($d < 5)
4 {
5 	echo 'The value of $d is '.$d.'<BR>';
6 	$d++;
7 }

Here, we first declare a variable called $d and assign the value 1 to it.

Next, we have the while loop from lines 3 to 7.

On line 3, the while loop checks if the condition $d < 5 is true . If it is, it executes the statements inside the curly braces that follow. In other words, it executes the echo statement on line 5 and increments $d by 1 on line 6. As a result, $d becomes 2 .

Next, the while loop returns to line 3 to check if $d is still smaller than 5 . If it is, it executes the code inside the curly braces again. This process of checking and updating the value of $d continues until $d is no longer smaller than 5 . If you run the code above, you’ll get the following output:

The value of $d is 1
The value of $d is 2
The value of $d is 3
The value of $d is 4

At this point, you may notice that the while loop is very similar to the for loop. Indeed, in most cases, both of them serve the same purpose.

However, when using a while loop, one important difference is that we must remember to update the variable used for looping ( $d in this example). If we forget to do that, the while loop will run indefinitely, resulting in an infinite loop.

For instance, in our example, if we omit line 6 ( $d++; ), the while loop will never end as the value of $d will always be 1 , which is smaller than 5 . Got it? Good!

6.3.7 Do-while Loop

Last but not least, let’s move on to the do-while loop. This loop is very similar to the while loop except that the test condition is placed at the end of the loop. This means that the code within the curly braces of the loop will always be executed at least once.

The syntax of a do-while loop is

do {
//some tasks
}
 while (condition is true);

Note that a semicolon ( ; ) is required after the test condition. Here’s an example of how the loop works.

1 $e = 100;
2
3 do {
4 	echo 'The value is '.$e;
5 	$e++;
6 } while ($e<0);

On line 1, we first declare and initialize a variable $e with the value 100 .

Next, we have the do-while loop from lines 3 to 6. Within the loop, the program executes the echo statement on line 4 and increments the value of $e to 101 on line 5.

Finally, it reaches the test condition on line 6.

As the value of $e is not smaller than 0 , the test fails. The program exits the do-while loop and does not repeat the tasks in the loop. If you run the code above, you will get

The value is 100

as the output. Although the original value of $e does not meet the test condition ($e < 0 ), the code inside the curly braces is executed once as the test condition comes after the closing curly brace.

6.4 Other Topics in Flow Control

Great! We’ve covered all the main control structures in PHP. Before we end this chapter, I would like to cover a few more miscellaneous topics related to flow control in PHP.

6.4.1 Booleans

First, let’s talk about the bool data type. We encountered this data type in Chapter 4.3 and learned that it can only store one of two values – true or false.

In PHP, most values can be converted to true or false (i.e., converted to the bool data type).

Values that convert to false include:

  • numbers that represent zero (such as 0 and 0.0 )
  • the empty string (such as '' , which is made up of two single quotes with no text enclosed)
  • the string "0"
  • an array with zero elements, and
  • a special value called NULL .

On the other hand, most other values (such as 13.4 and "Hello" ) convert to true .

We’ve seen how control structures decide whether to execute a certain block of code depending on whether a condition evaluates to true or false . Suppose we have the following if statement:

if ("hello")
	echo 'if block';
else
echo 'else block';

If we run the statement above, we’ll get

if block

as the output.

This is because the string "hello" is converted to true . For any control structure, as long as a condition evaluates to true , regardless of whether it is the result of a comparison (e.g., $a < 5 ) or a value converted to true , the corresponding block of code will be executed.

In the if statement above, the if block is executed as the if condition ( "hello" ) evaluates to true . Got it? Good!

6.4.2 Break, Continue

Next, let’s discuss break and continue statements. These statements can be used to modify the behavior of our control structures.

We’ve already encountered the break statement when we talked about the switch statement previously. When a particular switch case is satisfied, the switch statement executes everything that follows until it encounters a break statement.

Besides using it in a switch statement, we can use the break statement in a loop. A break statement ends the execution of the loop it is in. Let’s look at an example:

for ($i = 0; $i < 50; ++$i){
	echo "$i<BR>";
	if ($i == 4)
	  break;
}

Here, we have an if statement inside a for loop. It is fairly common for us to nest one control structure inside another in programming.

Within the for loop, we first echo the value of $i . Next, we check if $i equals 4 . If it equals, we want the program to break out of the for loop. If you run the code above, you’ll get the following output:

0
1
2
3
4

If we do not have the break statement, the for loop should run 50 times, from $i = 0 to $i = 49 .

However, as we have the break statement, this loop only runs from $i = 0 to $i = 4 . This is because when $i equals 4 , the if condition ( $i == 4 ) evaluates to true . The break statement that follows then causes the program to break out of the for loop, skipping the rest of the iterations (from $i = 5 to $i = 49 ). Got it?

Next, we have the continue statement. This statement does not cause a loop to end prematurely. Instead, it causes the rest of the loop to be skipped for that particular iteration. Let’s look at an example:

for ($i = 0; $i < 6; ++$i) {
	echo '$i = '.$i.', ';
  	if ($i == 4)
	  continue;
  	echo 'First.';
 	echo 'Second.<BR>';
}

If you run the code above, you’ll get the following output:

$i = 0, First.Second.
$i = 1, First.Second.
$i = 2, First.Second.
$i = 3, First.Second.
$i = 4, $i = 5, First.Second.

Notice that when $i equals 4 , the text “First.Second.” does not appear? This is because when $i equals 4 , the continue statement caused the program to skip the statements echo 'First.';echo 'Second.<BR>';

for that iteration. Other than that, the code runs as per normal. Clear?

6.4.3 Alternative Syntax

Next, let’s move on to talk about an alternative syntax for control structures in PHP.

PHP offers an alternative syntax for some of its control structures, specifically the ifwhileforforeach , and switch structures.

This syntax involves changing opening braces to colons ( : ) and the last closing brace to endif;endwhile;endfor;endforeach; , or endswitch; respectively.

Let’s use an if statement to illustrate this. Suppose we want to display different outputs based on the value of $a , we can use the following if statement:

$a = 5;
if ($a == 5){
	echo '<BR>The value of $a is<BR>';
	echo $a;
}
else{
	echo 'Not five';
}

Alternatively, we can do it as follows:

$a = 5;
if ($a == 5):
	echo '<BR>The value of $a is<BR>';
	echo $a;
else:
	echo 'Not five';
endif;

Compare the two if statements carefully. Notice that in the second if statement above, we replaced both opening braces with a colon? In addition, we replaced the last closing brace with an endif; statement.

If you run the code above, you’ll get

The value of $a is
5

as the output for both syntaxes.

6.4.4 Displaying HTML code

Last but not least, let’s discuss a neat trick for outputting HTML code in control structures. So far, we have been using echo statements to output HTML code (such as the <BR> tag) in our control structures.

This technique is easy to use and works well with simple HTML code. However, it can get cumbersome if we have more complicated HTML code to output, especially if the code uses lots of single and double quotation marks. For instance, if we want to output the following HTML code

<a href = "names.php" target="_blank">The names are 'Aaron', 'Peter', 'James', 'Max', 'Jenny' and 'Don'.</a>
<img src="names.jpg" alt="Names" height="42" width="42">

using an echo statement, we need to escape a lot of quotation marks. In cases like that, we can use a neat trick to switch between PHP and HTML code.

For demonstration purposes, let’s suppose we want to use a for loop to output the HTML code <h1>Hello</h1> three times, the code below shows how we can do it (using the alternative syntax mentioned in the previous section):

1 <?php
2 	for ($i = 0; $i < 3; ++$i):
3 		echo '<h1>Hello</h1>';
4 	endfor;
5 ?>

This loop uses an echo statement to output the HTML code. Alternatively, if we do not want to use echo statements, we can do it as follows:

1 <?php
2 	for ($i = 0; $i < 3; ++$i): ?>
3 		<h1>Hello</h1>
4 	<?php endfor;
5 ?>

Study the two loops carefully, what differences do you notice?

First, notice that we added ?> to the end of line 2 in the second loop? This ?> tag closes the <?php opening tag on line 1.

When that happens, any code after line 2 in the second loop is no longer interpreted as PHP code. Instead, it is interpreted as HTML code. This explains why we do not need to use an echo statement to output <h1>Hello</h1> on line 3.

Next, on line 4, we open the PHP tag again. When PHP sees this opening tag, it knows that what follows is PHP code.

When it encounters the endfor; statement, it realizes that this is a for loop and searches for the condition to evaluate. When it finds it on line 2, it increments $i by 1 and runs line 3 again. This keeps repeating until the condition $i < 3 is no longer valid. Got it?

If you run the loops above, you’ll get “Hello” displayed as a <h1> heading three times in both cases.

Study the two loops carefully to appreciate how this technique works. It can be a bit confusing in the beginning. The main idea is to close the PHP tag before switching to HTML code and open it again after the HTML code. This makes it much more convenient to insert HTML code without having to use echo statements.