You can use AND/OR, but…
Let’s get straight to the short answer: PHP supports AND/OR instead of &&/||, but because they have lower precedence, they can cause incorrect wait behavior.
What is Lower precedence?
Lower precedence is the same as “lower priority”; in this context, we are talking about the order in which an operator is evaluated after other operators in the same expression.
In other words:
When PHP reads a line of code with multiple operators, it decides which parts to calculate first based on operator precedence.
Let’s look at some examples below to clarify the concept.
Using && / ||
$a = true;
$b = false;
$c = false;
//waited expression
$res = ($a && $b) || $c;
//typed expression (it's the same above)
$res = $a && $b || $c;
//practical example
if($res) {
echo 'it\'s true';
}
else {
echo 'it\'s false';
}
//output: it's falseThat makes sense, since express says: if variables a and b are true, or if variable c is true, show “true”, otherwise show “false”.
Using and / or
$a = true;
$b = false;
$c = false;
//waited expression
$res = ($a and $b) or $c;
//typed expression (it isn't the same above)
$res = $a and $b or $c;
//practical example
if($res) {
echo 'it\'s true';
}
else {
echo 'it\'s false';
}
//output: it's trueDue to and has very low precedence in PHP, lower than the assignment operator =, so the expression is interpreted as:
($res = $a) and $b or $c;The rest of the expression, and $b or $c, is then evaluated and discarded because it is not assigned to anything. This logical operation uses the value of $a as its first operand (true).
Leave a Reply