Can someone explain me this behaviour of PHP?
$foo = ["bar" => "baz"];
var_dump($foo["bar"] ?? "" === "baz"); // dumps "baz"
var_dump($foo["foo"] ?? "" === "baz"); // dumps false
// with parenthesis it works
var_dump(($foo["bar"] ?? "") === "baz"); // dumps true
var_dump(($foo["foo"] ?? "") === "baz"); // dumps false
Tested in PHP 7.4 and PHP 8.2
What confuses me is that it can dump the operand OR the condition result depending on the condition result, if it is true, it dumps the operand, if it is false, it dumps the result.
This is a problem if you do something like
if ($options["foo"] ?? '' === 'option') {
// doe something if options.foo equals 'option'
}
this will not work, the condition will always be the value of options.foo, so as long as options.foo contains anything, the condition will evaluate to to true (non-strict)