Grouping Conditions in PHP
Although the and
operation has precedence
over or
, it is often more convenient to use
grouping parentheses to explicitly show the
precedence of operations:
<?php
$num = 3;
if ( ($num > 0 and $num < 5) or ($num > 10 and $num < 20) ) {
echo '+++';
} else {
echo '---';
}
?>
Of course, grouping can also be used in the case when you need your own priority of operations, and not the one that is obtained by default.
In the code below, specify the priority of operations explicitly:
<?php
$num = 3;
if ($num > 5 and $num < 10 or $num == 20) {
echo '+++';
} else {
echo '---';
}
?>
In the code below, specify the priority of operations explicitly:
<?php
$num = 3;
if ($num > 5 or $num > 0 and $num < 3) {
echo '+++';
} else {
echo '---';
}
?>
In the code below, specify the priority of operations explicitly:
<?php
$num = 3;
if ($num == 9 or $num > 10 and $num < 20 or $num > 20 and $num < 30) {
echo '+++';
} else {
echo '---';
}
?>