"baz"]; var_dump($foo["bar"] ?? "" === "baz"); // dumps "baz" var_dump($foo["foo"] ?? "" /> "baz"]; var_dump($foo["bar"] ?? "" === "baz"); // dumps "baz" var_dump($foo["foo"] ?? "" /> "baz"]; var_dump($foo["bar"] ?? "" === "baz"); // dumps "baz" var_dump($foo["foo"] ?? ""/>

Why does php return the operand rather than the condition result if you use a ?? operator on one side of the condition

34 Views Asked by At

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)

0

There are 0 best solutions below