PHP Control Structures

Control structures allow you to control the flow of your script—after all, if all a script could do was run from start to finish, without any control over which portions of the script are run and how many times, writing a programwould be next to impossible.

PHP features a number of different control structures—including some that, despite being redundant, significantly simplify script development. You should be very familiar with all of them, as they are one of the fundamental elements of the language’s structure.

Conditional Structures
Conditional structures are used to change the execution flow of a script based on one or more conditions. The most basic of these structures is the if-then-else construct, which executes one of two statements (or sets of statements enclosed in a code block) depending on whether a condition evaluates to true or false:

if(expression1) {

}
elseif(expression2) {
   // Note that the space between else and if is optional
}
else{

}

Here, if expression1 evaluates to true, the code block immediately following it is executed.
Otherwise, the interpreter attempts to execute the contents of the else portion of the statement. Note that you chain together several if-then-else statements by using the elseif construct instead of a simple else (you can also use else if, which is equivalent).

Naturally, if-then-else statements can be nested:

if(expression1) {
   if(expression2) {
     // Code
   }
   else{
      // More code
   }
}
else{
   if(expression3){
      // More core again.
   }
}

A special ternary operator allows you to embed an if-then-else statement inside an expression:

<?php
echo 10 == $x ? 'Yes' : 'No';
?>

The code above would be equivalent to the following:
<?php
if(10 == $x){
   echo 'Yes';
}
else{
   echo 'No';
}
?>

As you can see, the former expression is much more concise—and, if used properly, can make code much more readable. However, you should think of this operation as nothing more than a shortcut: used in excess, it can make your code difficult to understand and compromise its functionality, particularly if you start nesting several of these operations into each other.

The problem with if-then-else statements is that they tend to get rather complicated when you need to check a single expression against several different possible values. Imagine, for example, the not-so-uncommon situation in which you have a series of related if-then-else statements like the following:

<?php
$a = 0;
if($a){
   // Evaluates to false
}
elseif ($a == 0) {
   // Evaluates to true
}
else{
   // Will only be executed if no other conditions are met
}
?>

There are several problems here. First, you have to write a lot of code, which is difficult to maintain and understand. Second, the value of $a must be evaluated every time an if condition is encountered—which, in this case, is not a big problem, but could be if you needed to evaluate a complex expression. To mitigate this problem, PHP features the switch construct:

<?php
$a = 0;
switch($a){ // In this case, $a is the expression
   case true: // Compare to true
      // Evaluates to false
   break;
   case 0: // Compare to 0
      // Evaluates to true
   break;
   default:
      // Will only be executed if no other conditions are metbreak;
}
?>

A switch statement evaluates the initial expression ($a in this case) only once, and then compares it against the individual case values; if a match is found, it will continue to execute code until it encounters a break statement. Note that the use of break is required—or the interpreter will continue executing code even if it finds another case. Finally, if none of the test cases match, the interpreter executes the code block in the default block.

Iterative Constructs
Iterative constructs make it possible to execute the same portion of code multiple times. PHP has four of these, although only two of them are necessary to the functioning of a language.

The simplest iterative constructs are the while() and do…while() loops; they allow you to performa series of operations until a condition evaluates to true:

<?php
$i = 0;
while($i < 10){
   echo $i . PHP_EOL;
   $i++;
}

$i = 0;
do{
   echo $i . PHP_EOL;
   $i++;
}while ($i < 10);
?>

As you can see, these two types of loop are very similar; the only significant difference is in when the condition is checked to determine whether the code inside the construct should be executed or not. In a while() loop, the check is performed every time the execution point enters the loop—this means that, if the condition is never true, the code inside the loop will never be  executed. In a do…while() loop, on the other hand, the check takes place at the end of each iteration of the loop—meaning that, even if the condition never evaluates to true, the contents of the loop will be executed at least once.

The for and foreach constructs are specialized looping mechanisms that can be used to essentially encapsulate a while() loop in a slightly more readable form:

<?php
for($i = 0; $i < 10; $i++) {
   echo $i . PHP_EOL;
}
?>

As you can see, the for declaration contains three portions, separated by semicolons.

The first one contains an instruction (or series of instructions separated by a comma) that is executed once before the loop has begun. The second one contains a condition that is checked at the beginning of every iteration the loop, and the third one an instruction (or, again, a set of instructions separated by a comma) that is executed at the end of every iteration. Therefore, the code above would be equivalent to writing the following:

<?php
$i = 0;
while($i < 10) {
   echo $i . PHP_EOL;
   $i++;
}
?>

Breaking and Continuing
The break keyword, which we encountered briefly in the earlier section about the switch statement, can also be used to immediately exit a loop; it takes an optional parameter, which allows you to exit from multiple nested loops:

<?php
$i = 0;
while(true){
   if($i == 10) {
      break;
   }
   echo $i . PHP_EOL;
   $i++;
}

for($i = 0; $i < 10; $i++){
   for($j = 0; $j < 3; $j++){
      if(($j + $i) % 5 == 0){
         break 2; // Exit from this loop and the next one.
      }
   }
}
?>

There are cases in which, rather than terminating a loop, you simply want to skip over the remainder of an iteration and immediately skip over to the next. This is done with the continue statement—like with break, you can provide it an integer parameter to specify the level of nesting to which the it applies. For example, the following code will only output numbers between 0 and 3, and between 6 and 9:

<?php
for($i = 0; $i < 10; $i++) {
   if($i > 3 && $i < 6) {
      continue;
   }
   echo $i . PHP_EOL;
}
?>

Next Topic | Previous Topic

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *