小编典典

+数组中的运算符在PHP中?

php

$test = array(‘hi’);
$test += array(‘test’,’oh’);
var_dump($test);

+PHP中的数组意味着什么?


阅读 362

收藏
2020-05-26

共1个答案

小编典典

引用PHP语言操作员手册

+运算符返回添加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而右侧数组中的匹配元素将被忽略。

所以如果你这样做

$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)
)

因此,的逻辑+等效于以下代码段:

$union = $array1;

foreach ($array2 as $key => $value) {
    if (false === array_key_exists($key, $union)) {
        $union[$key] = $value;
    }
}

如果您对C级实现的细节感兴趣,请访问

  • php-src / Zend / zend_operators.c

请注意,这+array_merge()组合数组的方式不同:

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
)

有关更多示例,请参见链接的页面。

2020-05-26