开发者

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

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)


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']) {

    }
}


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜