[Solved] counter-intuitive behavior of isset()


This shouldn’t be at all surprising.

Why it evaluates true when $foo is a string: $foo[‘name’] is the same thing as asking for the zeroeth character of $foo when it’s a string – because ‘name’ or ‘camel’ or ‘cigar’ or ‘any other string’ will be coerced into an integral value in that context.

array_key_exists() might also not be quite what you want, since it will return true if the key is set even if it has the null value.

in_array() would also be bad, as it will quietly search a string or an array without complaint.

Consider instead:

 $name = ( is_array( $foo ) && isset( $foo['name'] ) ) ? $foo['name'] : $foo;

Note that this does not take into account whatever you do plan to do if array and value for key ‘name’ is null, or if string and $foo is null, etc., which isn’t a shortcoming on the part of the language but rather a piece of logic specific to your application.

1

solved counter-intuitive behavior of isset()