gpt4 book ai didi

php - + PHP中数组的运算符?

转载 作者:IT老高 更新时间:2023-10-28 11:41:23 25 4
gpt4 key购买 nike

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

+对于PHP中的数组是什么意思?

最佳答案

引自 PHP Manual on Language Operators

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

所以+的逻辑等价于如下代码段:

$union = $array1;

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

如果您对 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
)

查看链接页面了解更多示例。

关于php - + PHP中数组的运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2140090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com