[Previous] [Contents] [Next]

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.

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";

[Previous] [Contents] [Next]