Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...