+运营商在PHP数组? [英] + operator for array in PHP?
本文介绍了+运营商在PHP数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$test = array('hi');
$test += array('test','oh');
var_dump($test);
这是什么 +
意味着在PHP数组?
推荐答案
+运算返回附加到左手阵列右手阵列;对于同时存在于两个阵列的键,从左侧数组中的元素将被使用,并且从右侧阵列的匹配元素将被忽略。
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
所以,如果你
$array1 = ['one', 'two', 'foo' => 'bar'];
$array2 = ['three', 'four', 'five', 'foo' => 'baz'];
print_r($array1 + $array2);
您将获得
Array
(
[0] => one // preserved from $array1 (left-hand array)
[1] => two // preserved from $array1 (left-hand array)
[foo] => bar // preserved from $array1 (left-hand array)
[2] => five // added from $array2 (right-hand array)
)
所以逻辑 +
等同于下面的代码片段:
So the logic of +
is equivalent to the following snippet:
$union = $array1;
foreach ($array2 as $key => $value) {
if (false === array_key_exists($key, $union)) {
$union[$key] = $value;
}
}
如果您有兴趣在C级实现头的细节
If you are interested in the details of the C-level implementation head to
请注意,该 +
是如何不同 array_merge()
将结合数组:
Note, that +
is different from how array_merge()
would combine the arrays:
print_r(array_merge($array1, $array2));
会给你
Array
(
[0] => one // preserved from $array1
[1] => two // preserved from $array1
[foo] => baz // overwritten from $array2
[2] => three // appended from $array2
[3] => four // appended from $array2
[4] => five // appended from $array2
)
请参阅链接的网页更多的例子。
See linked pages for more examples.
这篇关于+运营商在PHP数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文