Default array values if key doesn't exist?

PhpArraysDefault

Php Problem Overview


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

Php Solutions


Solution 1 - Php

I know this is an old question, but my Google search for "php array default values" took me here, and I thought I would post the solution I was looking for, chances are it might help someone else.

I wanted an array with default option values that could be overridden by custom values. I ended up using array_merge.

Example:

<?php
    $defaultOptions = array("color" => "red", "size" => 5, "text" => "Default text");
    $customOptions = array("color" => "blue", "text" => "Custom text");
    $options = array_merge($defaultOptions, $customOptions);
    print_r($options);
?>

Outputs:

Array
(
    [color] => blue
    [size] => 5
    [text] => Custom text
)

Solution 2 - Php

As of PHP 7, there is a new operator specifically designed for these cases, called Null Coalesce Operator.

So now you can do:

echo $items['four']['a'] ?? 99;

instead of

echo isset($items['four']['a']) ? $items['four']['a'] : 99;

There is another way to do this prior the PHP 7:

function get(&$value, $default = null)
{
    return isset($value) ? $value : $default;
}

And the following will work without an issue:

echo get($item['four']['a'], 99);
echo get($item['five'], ['a' => 1]);

But note, that using this way, calling an array property on a non-array value, will throw an error. E.g.

echo get($item['one']['a']['b'], 99);
// Throws: PHP warning:  Cannot use a scalar value as an array on line 1

Also, there is a case where a fatal error will be thrown:

$a = "a";
echo get($a[0], "b");
// Throws: PHP Fatal error:  Only variables can be passed by reference

At final, there is an ugly workaround, but works almost well (issues in some cases as described below):

function get($value, $default = null)
{
    return isset($value) ? $value : $default;
}
$a = [
    'a' => 'b',
    'b' => 2
];
echo get(@$a['a'], 'c');      // prints 'c'  -- OK
echo get(@$a['c'], 'd');      // prints 'd'  -- OK
echo get(@$a['a'][0], 'c');   // prints 'b'  -- OK (but also maybe wrong - it depends)
echo get(@$a['a'][1], 'c');   // prints NULL -- NOT OK
echo get(@$a['a']['f'], 'c'); // prints 'b'  -- NOT OK
echo get(@$a['c'], 'd');      // prints 'd'  -- OK
echo get(@$a['c']['a'], 'd'); // prints 'd'  -- OK
echo get(@$a['b'][0], 'c');   // prints 'c'  -- OK
echo get(@$a['b']['f'], 'c'); // prints 'c'  -- OK
echo get(@$b, 'c');           // prints 'c'  -- OK

Solution 3 - Php

This should do the trick:

$value =  isset($items['four']['a']) ? $items['four']['a'] : 99;

A helper function would be useful, if you have to write these a lot:

function arr_get($array, $key, $default = null){
    return isset($array[$key]) ? $array[$key] : $default;
}

Solution 4 - Php

As of PHP7.0 you can use the null coalescing operator ??

$value = $items['one']['two'] ?? 'defaut';

For <5.6

You could also do this:

$value =  $items['four']['a'] ?: 99;

This equates to:

$value =  $items['four']['a'] ? $items['four']['a'] : 99;

It saves the need to wrap the whole statement into a function!

Note that this does not return 99 if and only if the key 'a' is not set in items['four']. Instead, it returns 99 if and only if the value $items['four']['a'] is false (either unset or a false value like 0).

Solution 5 - Php

The question is very old, but maybe my solution is still helpful. For projects where I need "if array_key_exists" very often, such as Json parsing, I have developed the following function:

function getArrayVal($arr, $path=null, $default=null) {
	if(is_null($path)) return $arr;
	$t=&$arr;
	foreach(explode('/', trim($path,'/')) As $p) {
		if(!array_key_exists($p,$t)) return $default;
		$t=&$t[$p];
	}
	return $t;
}

You can then simply "query" the array like:

$res = getArrayVal($myArray,'companies/128/address/street');

This is easier to read than the equivalent old fashioned way...

$res = (isset($myArray['companies'][128]['address']['street']) ? $myArray['companies'][128]['address']['street'] : null);

Solution 6 - Php

Not that I know of.

You'd have to check separately with isset

echo isset($items['four']['a']) ? $items['four']['a'] : 99;

Solution 7 - Php

Use Array_Fill() function

http://php.net/manual/en/function.array-fill.php

$default = array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         );
$arr = Array_Fill(1,3,$default);
print_r($arr);

This is the result:

Array
(
    [1] => Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
            [d] => 4
        )

    [2] => Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
            [d] => 4
        )

    [3] => Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
            [d] => 4
        )

)

Solution 8 - Php

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;
}

Solution 9 - Php

You can use DefaultArray from Non-standard PHP library. You can create new DefaultArray from your items:

use function \nspl\ds\defaultarray;
$items = defaultarray(function() { return defaultarray(99); }, $items);

Or return DefaultArray from the items() function:

function items() {
    return defaultarray(function() { return defaultarray(99); }, 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,
         ),
    ));
}

Note that we create nested default array with an anonymous function function() { return defaultarray(99); }. Otherwise, the same instance of default array object will be shared across all parent array fields.

Solution 10 - Php

In PHP7, as Slavik mentioned, you can use the null coalescing operator: ??

Link to the PHP docs.

Solution 11 - Php

Currently using of php 7.2

>>> $a = ["cat_name"=>"Beverage", "details"=>"coca cola"];
=> [
     "cat_name" => "Beverage",
     "details" => "coca cola",
   ]
>>> $a['price']
PHP Notice:  Undefined index: price in Psy Shell code on line 1
=> null
>>> $a['price'] ?? null ? "It has price key" : "It does not have price key"
=> "It does not have price key"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncgwebprojectsView Question on Stackoverflow
Solution 1 - PhpHein Andre GrønnestadView Answer on Stackoverflow
Solution 2 - PhpSlavik MeltserView Answer on Stackoverflow
Solution 3 - PhpMārtiņš BriedisView Answer on Stackoverflow
Solution 4 - PhpEric KeyteView Answer on Stackoverflow
Solution 5 - PhpGerfriedView Answer on Stackoverflow
Solution 6 - PhpknittlView Answer on Stackoverflow
Solution 7 - PhprostamianiView Answer on Stackoverflow
Solution 8 - PhpYnhockeyView Answer on Stackoverflow
Solution 9 - PhpIhor BurlachenkoView Answer on Stackoverflow
Solution 10 - PhpNikolai R KristiansenView Answer on Stackoverflow
Solution 11 - PhpBishal UdashView Answer on Stackoverflow