Zaptree
Zaptree

Reputation: 3803

PHP ternary statement using 'and'

Ok so I just realized some wierd behavior with PHP and would like to know why this happens. So running this code:

 var_dump( true and false ? 'one' : 'two' );

Outputs

boolean true

instead of 'two' as you would expect... The problem appears to be using 'and'.

Running:

var_dump( true && false ? 'one' : 'two' );

outputs

string 'two' (length=3)

just as expected. Why does using 'and' instead of '&&' cause this weird behavior? Are they not supposed to be the same?

Upvotes: 5

Views: 71

Answers (2)

Pavel Strakhov
Pavel Strakhov

Reputation: 40512

It's because and have lower priority than && and ?:.

Upvotes: 3

rid
rid

Reputation: 63590

That's because ?: has higher precedence than and, but lower than &&.

Upvotes: 5

Related Questions