Web Database Applications with PHP \& MySQLWeb Database Applications with PHP \& MySQLSearch this book

2.2. Conditions and Branches

The control structures in PHP are similar in syntax to those in other high-level programming languages.

Conditionals add control to scripts and permit branching so that different statements are executed depending on whether expressions are true or false. There are two branching statements in PHP: if, with the optional else clause, and switch, usually with two or more case clauses.

2.2.1. if...else Statement

The if statement conditionally controls execution and its use in PHP is as in any other language. The basic format of an if statement is to test whether a condition is true and, if so, to execute one or more statements.

The following if statement executes the echo statement and outputs the string when the conditional expression, $var is greater than 5, is true:

if ($var > 5)
  echo "The variable is greater than 5";

The if statement executes only the one, immediately following statement.

Multiple statements can be executed as a block by encapsulating the statements within braces. If the expression evaluates as true, the statements within braces are executed. If the expression isn't true, none of the statements are executed. Consider an example in which three statements are executed if the condition is true:

if ($var > 5)
{
  echo "The variable is greater than 5.";
  // So, now let's set it to 5
  $var = 5;
  echo "In fact, now it is equal to 5.";
}

The if statement can have an optional else clause to execute a statement or block of statements if the expression evaluates as false. Consider an example:

if ($var > 5)
  echo "Variable greater than 5";
else
  echo "Variable less than or equal to 5";

It's also common for the else clause to execute a block of statements in braces, as in this example:

if ($var > 5)
{
  echo "Variable is less than 5";
  echo "-----------------------";
} 
else
{
  echo "Variable is equal to or larger than 5";
  echo "-------------------------------------";
}

Consecutive conditional tests can lead to examples such as:

if ($var < 5)
  echo "Value is very small";
else
  if ($var < 10)
    echo "Value is small";
  else
    if ($var < 20)
      echo "Value is big";
    else
      if ($var < 30)
        echo "Value is very big";

If consecutive, cascading tests are needed, the elseif statement can be used. The choice of which method to use is a matter of personal preference. This example has the same functionality as the previous example:

if ($var < 5)
  echo "Variable is very small";
elseif ($var < 10)
  echo "Variable is small";
elseif ($var < 20)
  echo "Variable is big";
elseif ($var < 30)
  echo "Variable is very big";

2.2.2. switch Statement

The switch statement can be used as an alternative to if to select an option from a list of choices:

switch ($menu)
{
  case 1:
    echo "You picked one";
    break;
  case 2:
    echo "You picked two";
    break;
  case 3:
    echo "You picked three";
    break;
  case 4:
    echo "You picked four";
    break;
  default:
    echo "You picked another option";
}

This example can be implemented with if and elseif, but the switch method is usually more compact, readable, and efficient to type. The use of break statements is important: they prevent execution of statements that follow in the switch statement and continue execution with the statement that follows the closing brace.

If break statements are omitted from a switch statement, you get a bug. If the user chooses option 3, the script outputs not just:

 "You picked three"

but also:

 "You picked three. You picked four. You picked another option" 

The fact that break statements are needed is sometimes considered to be a feature but is more often a source of difficult-to-detect bugs.

2.2.3. Conditional Expressions

The most common conditional comparison is to test the equality of two expressions with the Boolean result of true or false. Equality is tested with the double-equal operator, ==. Consider an example:

$var = 1;

if ($var == 1)
  echo "Equals one!";

If $var is equal to 1, the example evaluates as true and prints the message. If the example evaluates as false, nothing is printed.

Inequality can be tested with the != inequality operator:

$var = 0;

if ($var != 1)
  echo "Does not equal one!";

This evaluates as true and prints the message if $var isn't equal to 1. The operator != is usually referred to as the not equals operator, because the exclamation mark character negates an equality expression.

WARNING: If the equality operator == and the assignment operator = are unfamiliar beware: they are easy to inadvertently interchange. This is a very common bug and hard to detect.

The incorrectly formed conditional expression ($var = 1) always evaluates as true, because the assignment that actually occurs always succeeds and, therefore, is always true.

The error of incorrectly replacing an assignment with == is a far less common mistake. However, it's also difficult to detect because an incorrectly written assignment of $var == 1; is quietly evaluated as true or false with no effect on $var.

Expressions can be combined with parentheses and with the Boolean operators && (and) and || (or). For example, the following expression returns true and prints the message if $var is equal to either 3 or 7:

if ($var == 3) || ($var == 7)
  echo "Equals 3 or 7";

The following expression returns true and prints the message if $var equals 2 and $var2 equals 6:

if ($var == 2) && ($var2 == 6)
  echo "The variables are equal to 2 and 6";

Interestingly, if the first part of the expression ($var == 2) evaluates as false, PHP doesn't evaluate the second part of the expression ($var2 == 6), because the overall expression can never be true; both conditions must be true for an && (and) operation to be true. This short-circuit evaluation property has implications for design; to speed code, write the expression most likely to evaluate as false as the left-most expression, and ensure that computationally expensive operations are as right-most as possible.

WARNING: Never assume that expressions combined with the Boolean operators && and || are evaluated. PHP uses short-circuit evaluation when determining the result of a Boolean expression.

More complex expressions can be formed through combinations of the Boolean operators and the liberal use of parentheses. For example, the following expression evaluates as true and prints the message if one of the following is true: $var equals 6 and $var2 equals 7, or $var equals 4 and $var2 equals 1.

if ((($var == 6) && ($var2 == 7)) ||
   (($var == 4) && ($var2 == 1)))
  echo "Expression is true";

As in assignment expressions, parentheses ensure that evaluation occurs in the required order.

Equality and inequality are the two basic comparisons, but numbers are also compared to determine which is greater or lesser. Consider the following examples:

// Returns true if $var is less than 5
if ($var < 5)
  echo "Less than 5";

// Returns true if $var is less than or equal to 5
if ($var <= 5)
  echo "Less than or equal to 5";

// Returns true if $var is greater than 5
if ($var > 5)
  echo "Larger than 5";

// Returns true if $var is greater than or equal to 5
if ($var >= 5)
  echo "Equal to or larger than 5";

There is a new operator in PHP4, the is-identical operator ===. This isn't found in other languages and returns true only if the expression evaluates as equal and the arguments are of the same type. Consider an example:

// Returns true, since both are integers and equal
if (5 === 5)
  echo "Same types and value";

// Returns false, since there are mixed types
// (5.0 is a float, and 5 is an integer)
if (5.0 === 5)
  echo "This never prints!";

// The normal equality check would return true
if (5.0 == 5)
  echo "This always prints";
NOTE: The conditional expressions described here can compare strings but usually not with the expected results. If strings need to be compared—a common requirement—use the PHP string library function strcmp( ).

The strcmp( ) function is a string function used in this book and is discussed in more detail later in Section 2.6.

Any of the Boolean expressions we have discussed can be negated with an exclamation mark !, the unary not operator. The following two expressions are equivalent:

if (!($var != 1))
  echo "variable is one";

if ($var == 1)
  echo "variable is one";

So are the following:

if ($var < 10)
  echo "less than 10";

if (!($var >= 10))
  echo "less than 10";

Probably the most common use of the unary not operator is to check if a function call fails, and we often use this with the database functions in later chapters.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.