vaanipala
vaanipala

Reputation: 1291

When echoing boolean false, no text is printed

I found this question at http://www.phpinterviewquestions.com/php-interview-questions/operator-precedence/

Following operations are true or false? (Operator Precedence)

$one = true;
$two = null;
$a = isset($one) && isset($two);
$b = isset($one) and isset($two);

echo $a.'<br>';
echo $b;

I tried the above code. But only $b gets echoed as 1 (which is true). $a is not getting echoed. What could be the reason? I was expecting $a to be 0 (false).

Upvotes: 4

Views: 450

Answers (2)

drmad
drmad

Reputation: 620

I think @zerkms's answer (which is not wrong) is not the correct answer.

@vaanipala question (I think) is why $b is true and $a is false if both are generated by practically the same expression.

And yes, it's related to PHP operator precedence.

$a = isset($one) && isset($two); can be rewritten as

$a = (isset($one)) && (isset($two));

Nothing new or strange there, the parenthesis are practically redundant. But the and and or operators have lesser precedence of the assignment operator, so the line

$b = isset($one) and isset($two);

is internally grouped like:

($b = isset($one)) and (isset($two));

That first parenthesis has the value true (because = has greater precedence than and) which is assigned to $b. isset($two) is false, so that line at the end is processed as:

true and false

That operator result is false, but it goes nowhere. So... at the end $a is false and $b is true. Quod erat demonstrandum :-D

Upvotes: 1

zerkms
zerkms

Reputation: 254896

It's not about precedence, it's about implicit type casting

Use var_dump($a); instead of echo $a;

$a actually is false, but being echo'ed false is casted to empty string.

Upvotes: 6

Related Questions