A PHP script is a series of statements, each ended by a semicolon or a closing tag. A
block, { … }, groups statements and does not create a new variable scope.
Conditions in all the structures below convert to
bool. The manual’s
Control
Structures chapter is the reference.
if, elseif, else
if ( condition ) statement { elseif ( condition ) statement } [ else statement ]
A statement may be a single statement or a block. else if written as two
words is an else whose statement is another if; it works with
braces. In the colon form else if is a
parse error and elseif must be used.
while and do-while
while ($i < 3) { $i++; }
do {
$i--;
} while ($i > 0);
while tests the condition first. do-while tests it after
running the body, so the body runs at least once. do-while has no colon
form.
for
for ( [init {, init}] ; [test {, test}] ; [step {, step}] ) statement
The first group runs once. The test group runs before each iteration, and the last of
its comma-separated expressions decides whether to continue. Any group can be empty,
and an empty test counts as true, so for (;;) is an endless loop.
foreach
foreach ($array as $value) { /* ... */ }
foreach ($array as $key => $value) { /* ... */ }
foreach ($array as &$value) { $value *= 2; }
unset($value);
foreach ($rows as [$id, $name]) { /* ... */ }
foreach ($rows as ['id' => $id]) { /* ... */ }
- Arrays and objects can be iterated. An object gives its visible properties, or,
if it implements
Traversable, the values of its iterator. Other types give a warning. - A by-value loop iterates over the array as it was when the loop started. Changes to the array inside the loop do not affect the elements visited.
- A by-reference loop works on the live array, so elements added during the loop are
visited. Afterwards the loop variable still refers to the last element, so call
unset()on it. foreachdoes not move the internal array pointer used bycurrent()andnext().- The destructuring forms
need PHP 5.5 with
list()and PHP 7.1 with square brackets.
switch
switch ($value) {
case 1:
case 2:
echo "one or two";
break;
default:
echo "something else";
}
break- The subject is evaluated once, and compared with each
caseexpression using==, in order.matchis the strict, expression-based alternative. - Without
break, execution continues into the statements of the nextcase. Empty cases can be stacked. defaultruns if no case matches. It may be placed anywhere; more than onedefaultis a compile error.- A
caseended with a semicolon rather than a colon is deprecated since PHP 8.5. - Inside a
switch,continuebehaves likebreak. PHP warns about it, andcontinue 2is usually meant.
break and continue
break leaves the current for, foreach,
while, do-while or switch. continue
starts the next iteration of a loop. Both take an optional positive integer for how
many enclosing structures to act on:
foreach ($rows as $row) {
foreach ($row as $cell) {
if ($cell === null) {
continue 2; // next row
}
}
}
The level must be a literal positive integer: a variable, or break 0, is
a compile error. Using either statement outside a loop or switch is a
compile error.
return
return ends the current function and gives its value. In a file included
with include or require, a top-level return stops
running that file and hands the value to the includer. In the main script it ends the
script. See Functions and
Include.
goto
goto label; jumps to label: in the same file and the same
function (PHP 5.3). A label is an identifier followed by a colon. It is
case-sensitive.
for ($i = 0; $i < 100; $i++) {
while ($j--) {
if ($j === 17) {
goto found;
}
}
}
echo 'not found';
found:
echo 'j reached 17';
goto: leaving nested loops- The target must be in the same function or the top level of the same file. A label in another function is an error.
- Jumping into a loop or
switchis a compile error. Jumping out of one is allowed. - The label cannot be a variable.
declare
A declare statement sets compile-time directives for the rest of the file
or for a block. strict_types, encoding and ticks
are described under
Declare directives.
Alternative syntax
Control structures can use a colon instead of an opening brace and a keyword instead of a closing brace. It is used mainly in templates, where closing keywords are easier to read across HTML.
| Structure | Form |
|---|---|
if | if (…): … elseif (…): … else: … endif; |
while | while (…): … endwhile; |
for | for (…): … endfor; |
foreach | foreach (…): … endforeach; |
switch | switch (…): … endswitch; |
declare | declare (…): … enddeclare; |
- Braces and the colon form cannot be mixed in one structure.
do-whilehas no alternative form.- Nothing, not even white space, may be output between
switch (…):and the firstcase. A line break directly after?>is fine, because the closing tag removes it.
<?php if ($items): ?>
<ul>
<?php foreach ($items as $item): ?>
<li><?= htmlspecialchars($item) ?></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>Nothing here.</p>
<?php endif; ?>
Other statements
| Statement | Meaning |
|---|---|
echo $a, $b; | Outputs one or more strings. It is a language construct and has no return value |
print $a; | Outputs one string. As an expression it gives 1 |
unset($a, $b); | Destroys variables, or removes array elements and properties. Cannot be used as an expression |
global $a; | Imports global variables |
static $a = 0; | Declares a static variable |
exit;, die; | End the script, optionally with a status code or message. Since PHP 8.4 they are real functions that can be called by name, while the old forms without parentheses still parse |
; | The empty statement |
eval
eval($code) compiles and runs a string as PHP in the current scope. The
string starts in PHP mode, so it does not begin with a tag. It gives
null unless the code uses return. A parse error in the string
throws ParseError since PHP 7.0. Running text from a user this way runs
whatever it says.