5

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

shealtiel
  • 8,020
  • 18
  • 50
  • 82

4 Answers4

9

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.

Jonah
  • 9,991
  • 5
  • 45
  • 79
2

Try:

is_array($arr) && array_key_exists('key', $arr)
ncuesta
  • 760
  • 4
  • 12
  • This doesn't answer my question, but it wasn't clear enough. Edited it, please give another look – shealtiel Dec 21 '10 at 00:07
  • If it is **not** set, it will throw a Notice. What you can do is check first `isset($arr) && is_array($arr)`. – ncuesta Dec 21 '10 at 00:12
0

Maybe you can consider a generic get() function for safe-retrieving data from arrays:

/*
    Get with safety 
    @author: boctulus

    @param array 
    @param index1
    @param index2
    ..
*/
function get(){ 
    $numargs  = func_num_args();
    $arg_list = func_get_args();

    $v = $arg_list[0];  

    for ($i = 1; $i < $numargs; $i++) 
    {
            if (isset($v[$arg_list[$i]]))
            $v = $v[$arg_list[$i]];
        else
            return null;
    }

    return $v;
}

Use:

$arr = [];

var_dump( get($arr,'a','b') ); // NULL

$arr['a']['b'] = 'ab';
var_dump( get($arr,'a','b') ); // 'ab'
boctulus
  • 404
  • 9
  • 15
0

check if it exists first, then if its an array. Otherwise you will still get the same error.

if ( isset($arr['key'])) {
    if (is_array ($arr['key']) {

    }
}
profitphp
  • 8,104
  • 2
  • 28
  • 21