ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP Foundations

Basic Control Structures

04/05/2001

This article covers the basics of program control structures, including conditional statements and looping using the if and while statements in PHP. It also contains a brief note regarding embedding code blocks within other code blocks.

Conditional blocks

One of the most fundamental tools of any true programming language is the ability to control what code gets executed and under what conditions by using a conditional block. A conditional block can be thought of in English language terms as "if this, then that; otherwise something else". For instance: "If Billy has 5 dollars in his hand, then buy a candy bar; otherwise, cry." Today, we will discuss the basic structure and use of conditional blocks in our programs and introduce the ways we can use conditional blocks to compare one variable to another.

For this article, we'll be taking a look at the following PHP code:

<?php

 $dollars = 4;
  $have_candy = false;
 
  if($dollars == 5) {

   $have_candy = true;
   echo "Billy has a candy bar.<br />";

} else {

 echo "Billy could not afford any candy.<br />";
echo "Billy is crying.<br />";
}

echo "Billy went home.";

  if($have_candy) {

   echo "Billy ate his candy bar at home";
}
?>

The above is our first example of a conditional block and is the PHP version of our example mentioned in the introduction. When this code is executed, what will happen? Before we can properly answer this question, we first must learn some new syntax.

The if statement

The if statement is the most fundamental control structure available. Its function is to execute a "block" of code if and only if the statement provided to it is a "true" statement. In order to determine if a statement is indeed true, some comparison operators and their meaning must be introduced. Before that is covered, let's take a look at the if statement in general form:

If(conditions) {
  // Code if condition is true
 } [ else ] {
  // Code if condition is false
 }

Note: The presence of the brackets [ ] around the else portion of this general form indicates that it is not necessary to be a valid conditional. Another, incomplete general form of the if statement would be:

If(conditions) {
  // Code if condition is true
}

Now that we have a better understanding of the general form of an if statement, we can go back and examine our example. The parentheses of the first if statement contain $dollars == 5. Although it appears as if we are attempting (incorrectly) to assign the value 5 to the variable $dollars, in reality we are providing an execution condition for the code contained with the if statement. This condition (which can be read as $dollars must equal the value 5) will determine what code within that if statement is executed. There are many different comparison operators that are the foundation for building our conditionals, and they are listed below:

Comparison operators in PHP
$a == $b $a is equal to $b
$a != $b $a is not equal to $b
$a < $b $a is less than $b
$a > $b $a is greater than $b
$a <= $b $a is less than or equal to $b
$a >= $b $a is greater than or equal to $b

Looking back at our earlier example, we are now able to determine how our PHP code will behave. First, we initialized the variable $dollars with a value of 4 and the variable $have_candy with a Boolean value of false. Then, we compared the value of $dollars to see if it was equal to the constant value of 5. Since the value of dollars (4) was not equal to 5, $have_candy remained false and the output to the web browser was:

Billy could not afford any candy.
Billy is crying.
Billy went home.

What if we changed our conditions for the if statement? For instance, if we changed our conditional from equal (==) to less than or equal (<=), $have_candy would then be set to true and our output would be:

Billy has a candy bar
Billy went home.
Billy ate his candy bar at home.

Notice the behavior of the second if statement, which outputs "Billy ate his candy bar at home." In the first example, the variable $have_candy was false and, since there was no else statement for the second conditional block, it was simply skipped altogether. Another interesting behavior of the second if statement is the lack of any indication of what the variable $have_candy is being compared to. In cases such as this, where a variable is provided as the only condition to an if statement, the value of the variable is used to determine the behavior of the conditional. Therefore, since $have_candy had a value of true (referring to the second example), the conditional is considered to be true and, as expected, in the second example the code was executed.

Basic looping

If the ability to control what code in a script is run and under what conditions is the first fundamental part of any true programming language, then the ability to execute the same code multiple times is a very, very close second. Let's say you would like to write a script that outputs the numbers 1 through 5 on the web browser. How would you do this? One example would be:

<?php

  echo "1<br />";
  echo "2<br />";
  echo "3<br />";
  echo "4<br />";
  echo "5<br />";

?>

Although that doesn't seem too overly complicated, consider outputting the numbers 1 through 100, or 1000, or even 1,000,000? Obviously, writing a script that contains a million echo statements is, at best, impractical. Beyond that, there are many more complex examples where the same piece of code is executed numerous times that would be impossible to duplicate in such an inefficient fashion as above. It is with this in mind that we introduce the while statement.

The while statement

The while statement is the most fundamental looping mechanism available to a PHP programmer. Although fundamentally different, it holds many similarities in syntax to an if statement, with the only real difference being that a segment of code within a while block will be executed as long as the condition in the while block is met (see figure 1). The syntax for a while loop is as follows:

While(conditions) {
// This code will execute until the conditions    
// provided no longer evaluates to true
}

Also in PHP Foundations:

Using MySQL from PHP, Part 2

Using MySQL from PHP

MySQL Crash Course, Part 3

MySQL Crash Course, Part 2

MySQL Crash Course

Diagram of while loop.
Figure 1. Processing of a while loop.

Looking at our earlier counting example, a much easier and more effective way to produce the same results using a while loop would be:

<?php

  $count = 1;
	
  while($count <= 5) {
	
  echo $count."<br />";
   $count++;

  }

?>

As expected, the output for both examples is identical. Notice that by simply changing a few small aspects of this example, you can change the behavior of the while loop completely. (For example, instead of $count++ you could use $count += 2 and display only odd numbers.)

Infinite loops

What would have happened if we had forgotten to include the increment of $count in the body of our while loop? The variable $count would have never been incremented and therefore would have never reached the value of 5. Because of this, the conditional $count <= 5 would always evaluate to true and the program would never leave the while loop. This situation, called an infinite loop, is a common mistake by many programmers. Be careful when using while loops (or any type of loop discussed) to ensure that the program will eventually terminate.

Note: PHP will not allow a program to run longer than a specific period of time (determined by the system administrator) without special settings. Usually the default settings give any reasonable script enough time to complete without premature termination. However, there are times when a processor-intensive script's running time exceeds the default maximum time. In these cases, please consult the PHP documentation for instructions on how to extend the run time from within your PHP scripts.

In my next article I will discuss with you a more specialized version of a while loop called a for loop, as well as the methods behind multi-condition if statements.

Notes on embedding code blocks

When writing programs, it is often common to embed conditions, or even other loops, within other loops or conditionals. For example, the following will count from 1 to 5 but display the string "Magic Number!" before it displays the number 3:

<?php

  $count = 1;
	
  while($count <= 5) {
	
   if($count == 3) {

    echo "Magic Number!<br />";
			
   }

   echo $count."<br />";

   $count++;
  }

?>

This feature is an important part of the language and is used quite frequently; it can be used in any syntax where a code block (distinguished by the { and } symbols) exists.

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.