The left–operand is returned if it can be evaluated as: false, in the case of conjunction (a && b), or true, in the case of disjunction (a || b); otherwise the right–operand is returned.
Do equivalent operators exist in PHP?
// mysql_query() returns false, so the OR condition (die()) is executed. $result = mysql_query("some faulty query") || die("Error");
$a || $b
would return a boolean value
FALSE if either is truthy or both are falsy. It would NOT return the value of
$a was falsy:
$a = FALSE; $b = "I'm b"; echo $a || $b; // Prints "1", not "I'm b"
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b; // PHP 5.3 and later supports $c = $a ?: $b; echo $a ?: $b; // "I'm b"
PHP 7 introduces the
?? null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check
isset() on the left operand's array keys.
$a = null; $b = 123; $c = $a ?? $b; // $c is 123;
©2020 All rights reserved.