If I have an array full of information, is there any way I can a default for values to be returned if the key doesn't exist?

function items() {
    return array(
        'one' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
         'two' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
         'three' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
    );
}

And in my code

$items = items();
echo $items['one']['a']; // 1

But can I have a default value to be returned if I give a key that doesn't exist like,

$items = items();
echo $items['four']['a']; // DOESN'T EXIST RETURN DEFAULT OF 99

Thanks ?

share|improve this question
1  
php.net/array_key_exists. The manual can be quite useful. – vascowhite Mar 4 '12 at 14:45
Although array_key_exists would work, it may lead to performance issues with big arrays or lots of checks. It iterates over the entire array to make sure that key exists. Alternatively, isset() does one check and moves on. – CaseySoftware Mar 4 '12 at 14:56
What php needs is an array coalescing funcion, something that checks presence and gets the value or a default value if empty. – Jbm Mar 8 at 16:49

3 Answers

This should do the trick:

$value =  isset($items['four']['a']) ? $items['four']['a'] : 99;
share|improve this answer
I can't believe it's 2013 and there is no native funcion for this. What's the point of typing a whole expression twice? – Jbm Mar 8 at 16:47
Kohana has an Array helper, you can do this by calling Arr::get('key', $array, $default) really handy. – Mārtiņš Briedis Mar 9 at 21:27

Not that I know of.

You'd have to check separately with isset

echo isset($items['four']['a']) ? $items['four']['a'] : 99;
share|improve this answer

I don't know of a way to do it precisely with the code you provided, but you could work around it with a function that accepts any number of arguments and returns the parameter you're looking for or the default.

Usage:

echo arr_value($items, 'four', 'a');

or:

echo arr_value($items, 'four', 'a', '1', '5');

Function:

function arr_value($arr, $dimension1, $dimension2, ...)
{
    $default_value = 99;
    if (func_num_args() > 1)
    {
        $output = $arr;
        $args = func_gets_args();
        for($i = 1; $i < func_num_args(); $i++)
        {
            $outout = isset($output[$args[$i]]) ? $output[$args[$i]] : $default_value;
        }
    }
    else
    {
        return $default_value;
    }

    return $output;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.