Control Structures
The control structures in PHP are very similar to those used by the C language. Control structures are used to control the logical flow through a PHP script. PHP’s control structures have two syntaxes that can be used interchangeably. The first form uses C-style curly braces to enclose statement blocks, while the second style uses a more verbose syntax that includes explicit ending statements. The first style is preferable when the control structure is completely within a PHP code block. The second style is useful when the construct spans a large section of intermixed code and HTML. The two styles are completely interchangeable, however, so it is really a matter of personal preference which one you use.
if
The if
statement is a standard conditional found in most
languages. Here are the two syntaxes for the if
statement:
if(expr) { if(expr): statements statements } elseif(expr): elseif(expr) { statements statements else: } statements else { endif; statements }
The if
statement causes particular code to be executed if the
expression it acts on is true
. With the first form, you can omit the
braces if you need to execute only a single statement.
switch
The switch
statement can be used in place of a lengthy if
statement. Here are the two syntaxes for switch
:
switch(expr) { switch(expr): case expr: case expr: statements statements break; break; default: default: statements statements break; break; } endswitch;
The expression for each case
statement is compared against the ...
Get Webmaster in a Nutshell, Second 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.