I pass a variable $foo to a function. This input variable might be an array or a string. If it is an array, then I want to set:
$name = $foo['name']
And if it is a string, then I want to set:
$name = $foo
To accomplish this, I wrote the following code:
$name = isset($foo['name']) ? $foo['name'] : $foo
Unfortunately, this does not work.
The reason: isset($foo[‘name’]) returns TRUE when $foo is a string.
This behavior is suprising to me. I had expected isset($foo[‘name’]) to return FALSE because $foo[‘name’] is not set. Can someone explain this seemingly counter-intuitive behavior? Or suggest an alternative to isset() that returns FALSE on $foo[‘name’], when $foo is a string?
UPDATE:
See Christopher’s suggestion below:
$name = ( is_array( $foo ) && isset( $foo['name'] ) ) ? $foo['name'] : $foo;
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:
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.