November 28, 2014
Hot Topics:

PHP Control Structures

  • January 3, 2002
  • By Elizabeth Fulghum
  • Send Email »
  • More Articles »

Have you ever stopped to give directions to a lost driver from two states away? For the sake of providing an example, imagine your conversation went something like this:

"Hi, can you tell me how to get to route 50?"
"Sure, just follow this road, turn left onto the expressway, keep driving, and eventually you'll see the exit for route 50."

The directions above were linear and sequential: drive on this road, turn here, and then drive until you see the exit.

Obviously, they are horrible directions.

They don't tell the driver how long to drive on the road before they reach the expressway or that they might want to take a different route to avoid traffic if they tried to leave during rush hour.

If you wanted to give more exact and useful directions, you might say something like:

"Sure, just follow this road for two miles. If its not rush hour, you can take a left at the lights onto the expressway and follow it for another mile until you see the exit for route 50. If you hit it near rush hour, you'll want to avoid the expressway and just follow the road for another 5 miles to route 50."

Without Control Structures, PHP would be much like the first set of directions: linear, sequential, and not overly useful.

Control Structures are at the core of programming logic. They allow a script to react differently depending on what has already occurred, or based on user input, and allow the graceful handling of repetitive tasks.

In PHP, there are two primary types of Control Structures: Conditional Statements and Control Loops. In the last article, you saw some brief examples of Control Structures. This time, we will be taking a closer look at them.


Conditional Statements
Conditional Statements allow you to branch the path of execution in a script based on whether a single, or multiple conditions, evaluate to true or false. Put simply, they let you test things and perform various actions based on the results.

If Statements

Take a look at the following:

<?php
$x=1;

if ($x == 1) print '$x is equal to 1';
?>


This example illustrates the simplest kind of If Statement. If Statements always begin with "if", followed by a condition surrounded in parentheses. If the condition evaluates to true, then the statement or statements immediately following the condition will be executed. In this case, had the condition been false, nothing would have occurred and you would have seen a blank browser window when the script was run.

When you have more than one statement to be executed within a control structure, it's necessary to surround them with brackets:

<?php
$x=1;

if ($x == 1) {
   print '$x is equal to 1';
   $x++;
  
print 'now $x is equal to 2';
}
?>



Keep in mind that the positioning of the elements does not affect the execution of the script. All of the example arrangements below are perfectly valid not only for If Statements, but for every form of control loop.


if ($x == 1) print '$x is equal to 1';

if ($x == 1)
   print '$x is equal to 1';

if ($x == 1) { print '$x is equal to 1'; }

if ($x == 1) {
   print '$x is equal to 1';
}


In the interests of clarity, many programmers opt to use indenting and brackets even on one-line blocks of code; however, it is ultimately a matter of personal coding preference.

You can also include multiple conditions within parentheses. For the nested statements to execute, all of the conditions must evaluate to true.

<?php
$x=1;

if ($x == 1 OR $x == 2) print '$x is equal to 1 (or maybe 2)';
?>


Else Statements

As the name implies, Else Statements allow you to do something else if the condition within an If Statement evaluated to false:

<?php
$x=1;

if ($x == 2) {
print '$x is equal to 2';
} else {
   print '$x is equal to 1';
}
?>


Else If Statements


Thus far, we have been able to respond to one condition, and do something if that condition is not true. But what about evaluating multiple conditions? You could use a series of If Statements to test each potential condition, but in some situations that is not a suitable option. Here is where Else If Statements come in.

A combination of If and Else Statements, Else If Statements are evaluated sequentially if the condition within the If Statement is false. When a condition within an Else If Statement evaluates to true, the nested statements are parsed, the script stops executing the entire If/Else if/Else Structure. The rest of the script proceeds to be parsed.

Take a look at the following example:

<?php
$x=1;

if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
} else {
   print '$x does not equal 2 or 1';
}
?>


The final else statement can be left off if you do not want anything to happen if none of the If or Else If Statements are true:

<?php
$x=0;

if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
}
?>


In this case, since neither the condition within the If or Else if Conditions are true, and no Else Statement was provided, nothing would be outputted to the browser.

Switches

Switches are a good alternative to If/Else if/Else Statements in situations where you want to check multiple values against a single variable or condition. This is the basic syntax:

<?php
$var = "yes";

switch ($var) {
   case "yes":
     print '$var is equal to yes';
break;

   case "no":
    
print '$var is equal to no';
     break;
}
?>


After running this code snippet, much of what is here will probably make sense to you. In the first line of the switch statement, we have the identifier "switch" followed by a variable surrounded by parenthesis. Each case includes a possible value for the variable.

Switches execute a little differently than If/Else if/Else statements. Once a case value matches the value of the switch expression, every following statement is executed, including those following other cases.

To prevent this from happening, a break statement is used. "Break;" ends the execution of the switch statement, and lets the script continue execution; it can also be used in while or for loops.

Optionally, you may also include a special case called "default". This case works much like and Else Statement, and will execute if all the other cases are found to be false. This case should be the very last one you include.

<?php
$var = "yes";

switch ($var) {
   case "maybe":
     print '$var is equal to yes';
break;

   case "no":
    
print '$var is equal to no';
     break;
 
   default:
     print 'none of the other two cases were true, so this sentance will be printed out instead.';
}
?>


Similar to the Break Statement is the Exit Statement. Exit is particularly useful in situations where you run into what would be considered a "fatal error" (for example, if the user had entered a password that was incorrect) or any other time you needed to end the execution of a script before it naturally terminated.

<?php
$var = "yes";

switch ($var) {
   case "yes":
     print '$var is equal to yes';
     exit;
   case "no":
     print '$var is equal to no';
     break;
}

print "this will not be printed, because the script will have terminate before this line is reached";
?>


Unlike break, exit may be used anywhere in your scripts, inside or outside of control structures.


The Ternary Operator

Though Technically an Operator, not a Control Structure, the Ternary Operator, represented by "?", can be used as shorthand for simple If/Else Statements. It can only be used in situations where you want execute a single expression based on whether a single condition is true or false:

<?php
$x = 1;
($x==1) ? (print '$x is equal to 1') : (print '$x is not equal to 1');
?>


The condition is contained within the first set of parentheses. If it evaluates to true, then the expression within the second set of parentheses will be performed. Otherwise, the expression in the third set will be performed:

(condition) ? (executes if the condition is true) : (executes if the condition is false);


You will see how this can be particular useful a little later on.


Control Loops

Frequently in PHP there are instances where you need to perform repetitive tasks, such as formatting data pulled from a database, sending out emails to a mailing list, or cycling through the contents of an array. Control Loops allow you to perform these tasks almost effortlessly.

While Loops

While Loops are the simplest form of loops:

<?php
$x=1;

while ($x <=10) {
   print "$x<br>";
   $x++;
}
?>


When you run this snippet, you will see the numbers 1 through 10 printed on your screen. Take a look at the code. In many ways, it's very similar to an If Statement. First is the while identifier, followed by a condition surrounded by parentheses.

The statements nested within the loop will execute as long as the condition within the parentheses evaluates to true. Since the validity of the condition is checked before the loop is executed, if the condition is false, then the statements within the loop will not be executed at all.


Do...While Loops

Do...While Loops are close cousins of While Loops:

<?php
$x=11;

do {
print "$x<br>";
$x++;
} while ($x <=10);
?>


The primary difference in how these work is that the validity of the condition in a Do...While Loop is tested after the loop has itinerated once. This means that in the example above, $x would be printed out one time, and then the execution of the loop would end, because $x is greater than 10.


For Loops

<?php
for($x=1; $x<=10; $x++) {
print "$x<br>";
}
?>


The above is an example of a For Loop. For Loops are very similar to While Loops, but more convenient to use in many cases. They are also the most complex loops in PHP, borrowing syntax and function heavily from the C Programming language. This is the final control struture we will be covering in this article.

If you guessed that the above snippet would output the same result as the first example of a while loop, you would be right! Let's take a closer look at why it works like that.
Within the parentheses, For Loops take three expressions separated by semi-colons. The first expression is only executed one time, when the loop initializes. In this case, $x is created and given a value of zero.

The next expression is a condition that is checked each time the loop itinerates. Once the condition is false, the loop will stop executing. Just like a while loop, if the condition is found to be false on the first run, none of the statements within the loop will execute even once.

The final expression will be executed each time the loop itinerates after the nested statements have been parsed. Remember that there is no semi-colon after the final expression.

As you can see, this for loop performs the same function as the earlier While Loop, but far more concisely. Typically, it's best to use a For Loop in situations where you know how many elements you will be cycling through.


The Foreach Loop

This new loop was introduced in PHP version 4. Its used exclusively for looping through elements of an array, allowing you to easily print out or perform operations on elements within an array. To keep things from getting too complicated, we will wait cover this particular loop in detail when arrays are introduced.

Finally...
In this article we have covered the two types of Control Structures that PHP supports: Conditional Statements and Control Loops. These Structures are at the core of controlling program flow; the concepts introduced here will be used extensively from now on.

Next time, we will take take a look at pre-defined and user defined functions, which also play an important roll in the logical development and execution of a script.

Stay Tuned!

Things to Remember:

  • Control Structures are at the core of programming flow, allowing you to branch the execution of scripts based on input and easily handle repeatitive tasks.
  • There are two types of Control Structures in PHP: Conditional Statements and Control Loops.
  • Conditional Statements and Loops having only one nested statement do not require brackets, however programmers frequently use them to make code more understandable. Nested statements are often indented for the same reason.
  • Break; can be used to end the execution of the current case. It can also be used to break out of for loops and while loops. Exit; terminates the execution entire script, and may be used anywhere within the script.

Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been a fan ever since and frequently works as a freelance developer.

# # #






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel