Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: is_array on $arr['key'] with non existing 'key'

Tags:

php

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

like image 256
shealtiel Avatar asked Dec 20 '10 23:12

shealtiel


2 Answers

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.

like image 59
Jonah Avatar answered Sep 29 '22 18:09

Jonah


Try:

is_array($arr) && array_key_exists('key', $arr)
like image 24
ncuesta Avatar answered Sep 29 '22 17:09

ncuesta