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
    elsestatement

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):?> ...

Get Programming PHP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.