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
In PHP7, as Slavik mentioned, you can use the null coalescing operator:
??
Link to the PHP docs.
You can use DefaultArray from Non-standard PHP library. You can create new DefaultArray from your items:
Or return DefaultArray from the
items()
function: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.Use Array_Fill() function
http://php.net/manual/en/function.array-fill.php
This is the result:
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:
Outputs:
This should do the trick:
A helper function would be useful, if you have to write these a lot:
You could also do this:
This equates to:
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 initems['four']
. Instead, it returns 99 if and only if the value$items['four']['a']
is false (either unset or a false value like 0).