O'Reilly logo

Web Database Applications with PHP, and MySQL by David Lane, Hugh E. Williams

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required