PHP programming - Flow Controls and Loops
Frank Yap

In this section you will exercise on PHP flow controls and loops.
 
Resources

 
Lab Exercises

 
Exercise 1: Using if control structure

The following examples show the use of 'if' control structure.
 

A function can be directly used in the condition testing statement.
Analyze the in_array() function and understand how it affects the flow control.
 
$classIsOn = array ('Monday', 'Wednesday', 'Friday'); 
$today = date('l'); // returns 'Monday' ... 'Sunday' 
 
if (in_array ($today, $classIsOn)) 
echo "You have a class today, $today.<br>"; 
else 
echo "You don't have a class today, $today.<br>";
Output ---
You don't have a class today, Saturday.
 


 
A string can be used in testing a condition.
 
$today = date('l');     // returns 'Monday' ... 'Sunday' 
 
if ($today == "Monday") 
echo "You have a class today, $today.<br>"; 
else if ($today == "Wednesday") 
echo "You have a class today, $today.<br>"; 
else if ($today == "Friday") 
echo "You have a class today, $today.<br>"; 
else 
echo "You don't have a class today, $today.<br>";
Output ---
You don't have a class today, Saturday.
 


 
Multiple test conditions can be used in the if statement.
 
$temperature = rand(25, 102);      // rand($min, $max) returns random number in the range $min .. $max 
 
if (($temperature >= 68) && ($temperature < 85)) 
echo "Today is very comfortable, temperature is $temperature"."F.<br>"; 
else if ($temperature >= 85) 
echo "Today is hot, temperature is $temperature"."F.<br>"; 
else if ($temperature >= 35) 
echo "Today is chilly, temperature is $temperature"."F.<br>"; 
else 
echo "Today is cold, temperature is $temperature"."F.<br>";
Output ---
Today is chilly, temperature is 63F.
 


 

Exercise 2: Using switch control structure

The following examples show the switch control structures.
 

The switch operator compares the switch parameter $today with the case parameter strings to determine if the case block should be executed.
If there is a match then the statements in that block are executed until it hits break statement.
If there is no match then the default block is executed.
 
$today = date('l');     // returns 'Monday' ... 'Sunday' 
 
switch ($today){ 
case "Monday": 
echo "You have a class today, $today.<br>"; 
break; 
case "Wednesday": 
echo "You have a class today, $today.<br>"; 
break; 
case "Friday": 
echo "You have a class today, $today.<br>"; 
break; 
default: 
echo "You don't have a class today, $today.<br>"; 
break; 
}
Output ---
You don't have a class today, Saturday.
 


 
This example shows what happens if a break statement is missing.
Once there is a match no longer case comparing operation takes place.
 
$i = 0; 
 
switch ($i) { 
case 0: 
echo "i equals 0<br>"; 
case 1: 
echo "i equals 1<br>"; 
break; 
case 2: 
echo "i equals 2<br>"; 
break; 
}
Output ---
i equals 0
i equals 1
 


 
This is where break statement is intentionally removed.
All the cases with missing break statement are executed until a break statement is hit.
 
$i = 0; 
 
switch ($i) { 
case 0: 
case 1: 
case 2: 
echo "i is less than 3 but not negative"; 
break; 
case 3: 
echo "i is 3"; 
break; 
}
Output ---
i is less than 3 but not negative
 


Exercise 3: Using while control structure

The following examples show the while control structures.
 

While loop continues to execute the block until the termination condition is met.
 
$arr = array("apple", "orange", "pear", "mango"); 
 
$i = 0; 
$n = count($arr); 
while ($i < $n) { 
$a = $arr[$i]; 
echo $a ."<br>"; 
$i++; 
}
Output ---
apple
orange
pear
mango
 


 
Continue is used to skip some executions while looping. Continue statement sends execution to while statement.
 
$arr = array("apple", "orange", "potato", "mango"); 
echo "Fruits:<br>"; 
$i = 0; 
$n = count($arr); 
while ($i < $n) { 
$a = $arr[$i]; 
$i++; 
if ($a == "potato") continue; 
echo $a ."<br>"; 
}
Output ---
Fruits:
apple
orange
mango
 


 
This code will hang in the loop forever. Can you see the difference between this and the above codes.
It is better if you could code in a loop without an index variable, but there are many situations where you have to use one. When continue is used with an index variable it is important to carefully place the index increasing statement.
 
$arr = array("apple", "orange", "potato", "mango"); 
echo "Fruits:<br>"; 
$i = 0; 
$n = count($arr); 
while ($i < $n) { 
$a = $arr[$i]; 
if ($a == "potato") continue; 
echo $a ."<br>"; 
$i++; 
}
 


 
Break is used to terminate a loop.
 
$arr = array("apple", "orange", "potato", "mango"); 
$i = 0; 
$n = count($arr); 
while ($i < $n) { 
$a = $arr[$i]; 
if ($a == "potato") break; 
$i++; 

if ($i < $n) 
echo "Potato found at index \$i == $i.<br>"; 
else  
echo "Potato not found.<br>";
Output ---
Potato found at index $i == 2.
 


Exercise 4: Using foreach control structure

The following examples show the foreach control structures.
 

Foreach loops through the array elements presenting the key and value of an element in the specified variables.
The variable at the left side of the arrow gets key and the variable at the right gets value.
 
$arr = array ("one"=>1, "two"=>2, "three"=>3, "seventeen"=>17); 
 
foreach ($arr as $k => $v){ 
echo "$k => $v.<br>"; 
}
Output ---
one => 1.
two => 2.
three => 3.
seventeen => 17.
 


 
This example shows the foreach loop on a multidimensional array.
When key variable (left side of arrow) is not specified only variable part of an array element is provided.
 
$a = array(); 
$a[0][0] = "a"; 
$a[0][1] = "b"; 
$a[1][0] = "y"; 
$a[1][1] = "z"; 
 
foreach ($a as $v1){ 
foreach ($v1 as $v2){ 
echo "$v2<br>"; 


var_dump ($a);
Output ---
a
b
y
z
array(2) { [0]=> array(2) { [0]=> string(1) "a" [1]=> string(1) "b" } [1]=> array(2) { [0]=> string(1) "y" [1]=> string(1) "z" } }
 


 
This example shows how the array in the above example is created.
 
$a = array(); 
$a[0] = array ("a", "b"); 
$a[1] = array ("y", "z"); 
 
foreach ($a as $v1){ 
foreach ($v1 as $v2){ 
echo "$v2<br>"; 

}
Output ---
a
b
y
z
 


 
This example shows another way of creating the same array.
 
$a = array (array ("a", "b"), array ("y", "z")); 
 
foreach ($a as $v1){ 
foreach ($v1 as $v2){ 
echo "$v2<br>"; 

}
Output ---
a
b
y
z
 


Exercise 5: Using for control structure

The following examples show the 'for' control structures.
 

This is an example of a 'for' loop made difficult to read.
 
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
Output ---
12345678910
 


 
The initialization could be done outside of the for statement, then the initialization field is left blank.
Likewise if the post execution ($i++) is done inside the loop block then the post execution field is left blank.
 
$i = 1; 
$j = 0;  
for ( ; $i <= 10; ){ 
$j += $i; 
print $i; 
$i++; 
}
Output ---
12345678910
 


 
The code below can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count().
 
$people = array( 
array('name' => 'Kalle', 'salt' => 856412), 
array('name' => 'Pierre', 'salt' => 215863) 
); 
 
for($i = 0; $i < count($people); ++$i) { 
$people[$i]['salt'] = mt_rand(000000, 999999); 
}
 


 
The code below is the improved version of the example above. The array size is fetched only once.
 
$people = array( 
array('name' => 'Kalle', 'salt' => 856412), 
array('name' => 'Pierre', 'salt' => 215863) 
); 
 
$size = count($people); 
for($i = 0; $i < $size; ++$i) { 
$people[$i]['salt'] = mt_rand(000000, 999999); 
}



 

Homework Exercise

Start XAMPP Apache server.

Read the following code and guess the output from each case.
Edit this file and run again to get the output from each case.
See if your guess was right.
Capture the output and report it.

Manuals for list() and each() functions are at:
http://php.net/manual/en/function.list.php

echo "<br>Case 1 ----<br><br>"; 
 
$arr = array ('one','two','three','four','stop','five'); 
while (list(, $val) = each($arr)){ 
if ($val=='stop'){ 
break; //You could also write 'break1;' here. 

echo "$val<br>"; 
}  
 
echo "<br>Case 2 ----<br><br>"; 
 
$arr = array ('one','two','three','four','stop','five'); 
foreach ($arr as $key => $val){ 
if ($key >= 2){ 
break; //You could also write 'break1;' here. 

echo "$val<br>"; 
}  
 
echo "<br>Case 3 ----<br><br>"; 
 
$arr = array ('one','two','three','four','stop','five'); 
foreach ($arr as $val){ 
if ($val=='stop'){ 
break; //You could also write 'break1;' here. 

echo "$val<br>"; 
}