Php ternary expression using 'and'

Ok, so I just understood some weird behavior with PHP and would like to know why this is happening. So run this code:

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

Outputs

boolean true

instead of “two,” as you would expect ... The problem is using the “and”.

Duration:

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

exits

string 'two' (length=3)

as expected. Why use 'and' instead of '& &' cause this strange behavior? Shouldn't they be the same?

+5
source share
2 answers

This is because it ?:has a higher precedence than and, but lower &&.

+5
source

This is because they andhave a lower priority than &&and ?:.

+3
source

All Articles