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) {statementsstatementselse: }statementselse { 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 only need to
execute 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): caseexpr: caseexpr:statementsstatementsbreak; break; default: default:statementsstatementsbreak; break; } endswitch;
The expression for each case statement is compared against the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access