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

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Try:

is_array($arr) && array_key_exists('key', $arr)

2 Comments

This doesn't answer my question, but it wasn't clear enough. Edited it, please give another look
If it is not set, it will throw a Notice. What you can do is check first isset($arr) && is_array($arr).
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']) {

    }
}

1 Comment

Why not both in the same statement: if ( isset($arr['key']) && is_array ($arr['key']) ?
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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.