One of my colleges seem to have an 'undefined index' error on a code I wrote
This code of mine looks like this:
if ( is_array ($arr['key']))
My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key']))
?
Maybe the following is equivavlent: Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?
Thank you
Yes, use isset
, then is_array
.
if(isset($arr['key']) && is_array($arr['key'])) {
// ...
}
Because PHP uses short-circuit logic evaluation, it will stop before it gets to is_array()
, so you'll never get an error.
Try:
is_array($arr) && array_key_exists('key', $arr)
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