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):statementsstatements} elseif(expr) { elseif(expr):statementsstatements} else { else:statementsstatements} endif;
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 ...