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?
It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);
The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.
So, why does the ternary operator become so slow under some circumstances? Why does it depend on the value stored in the tested variable? The answer is really simple: the ternary operator always copies the value whereas the if statement does not. Why?
In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
That's because ?:
has higher precedence than and
, but lower than &&
.
It's because and
have lower priority than &&
and ?:
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With