Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

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

O'Reilly logo

Flow-Control Statements

PHP supports a number of traditional programming constructs for controlling the flow of execution of a program.

Conditional statements, such as if/else and switch, allow a program to execute different pieces of code, or none at all, depending on some condition. Loops, such as while and for, support the repeated execution of particular segments of code.

if

The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a statement. An if statement looks like:

if (expression)statement

To specify an alternative statement to execute when the expression is false, use the else keyword:

if (expression)
  statement
else statement

For example:

if ($user_validated)
  echo "Welcome!";
else
  echo "Access Forbidden!";

To include more than one statement in an if statement, use a block—a curly brace–enclosed set of statements:

if ($user_validated) {
  echo "Welcome!";
  $greeted = 1;
}
else {
  echo "Access Forbidden!";
  exit;
}

PHP provides another syntax for blocks in tests and loops. Instead of enclosing the block of statements in curly braces, end the if line with a colon (:) and use a specific keyword to end the block (endif, in this case). For example:

if ($user_validated):
  echo "Welcome!";
  $greeted = 1;
else:
  echo "Access Forbidden!";
  exit;
endif;

Other statements described in this chapter also have similar alternate style syntax (and ending keywords); they can be useful if you have large blocks of HTML inside your statements. For example:

<? if ($user_validated ...

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