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