PHP默认数组值,如果键不存在? [英] PHP default array values if key doesn't exist?
问题描述
如果我有一个数组充满了信息,有什么办法,我可以,如果该键不存在值默认被返回?
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,
),
);
}
在我的code
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数组默认值花了我这里,我想我会发布的解决方案我寻找,机会是它可能会帮助别人。
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.
我想用这可以通过自定义值覆盖默认选项值的数组。我结束了使用 array_merge 。
I wanted an array with default option values that could be overridden by custom values. I ended up using array_merge.
例如:
<?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);
?>
输出:
Array
(
[color] => blue
[size] => 5
[text] => Custom text
)
这篇关于PHP默认数组值,如果键不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!