2.6. Control Structures

To add power and convenience to your scripts, PHP supports a number of conditional statements, loops, and other control structures that allow us to manipulate data easily throughout your code.

The control structures supported by PHP are:

  • if

  • else

  • elseif/else if

  • while

  • do-while

  • for

  • foreach

  • break

  • continue

  • switch

  • return

  • require

  • include

  • require_once

  • include_once

  • goto

2.6.1. if, else, and else if

The most basic control structure is the if statement. It defines a block of code between curly braces ({}) that is to be executed only if a condition is met:

<?php

    $foo = 5;

    if($foo < 10) {
        echo "The condition was met. <br />";
    }

?>

In this program, nothing is output if $foo doesn't meet your condition. In some cases, this is an unacceptable result, ...

Get PHP for Absolute Beginners 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.