Does PHP support conjunction and disjunction natively?

Javascript employs the conjunction and disjunction operators.

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?

Answers:

Answer

PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:

// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");

Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:

Simply doing:

$a || $b

would return a boolean value TRUE or FALSE if either is truthy or both are falsy. It would NOT return the value of $b if $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"

Update for PHP 7

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;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.