Statements: If
An if
statement will execute code if a condition is true. If it's false, an
else
block can execute.
$count = 11;
if ($count < 10) {
echo "small";
} else if ($count < 20) {
echo "medium";
} else {
echo "large";
}
Conditions must have type bool
or be implicitly convertible to
bool
.
If the condition evaluates to to true
, the if
block is
executed. Otherwise, else if
conditions are evaluated in order until
one evaluates to true
, then its block is executed.
If none of the conditions evaluate to true
, and an else
block is
present, that will be executed instead.
Without Braces
Braces allow you to have multiple statements inside an if
statement. Braces are recommended, but they are optional.
if ($count < 10)
echo "small";
else
echo "big";
When no braces are present, an else
clause is associated with the
lexically nearest preceding if
or else if
.
if ($x)
echo "x is true";
if ($y)
echo "y is true";
else // Associated with the second if.
echo "y is not true";
The above code is equivalent to:
if ($x) {
echo "x is true";
}
if ($y) {
echo "y is true";
} else {
echo "y is not true";
}
Thank You!
Thank You! If you'd like to share more feedback, please file an issue.