+ operator for array in PHP?(+ PHP中数组的运算符?)
问题描述
$test = array('hi');
$test += array('test','oh');
var_dump($test);
+
对于PHP中的数组是什么意思?
What does +
mean for array in PHP?
推荐答案
引用 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
- php-src/Zend/zend_operators.c
请注意,+
与 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中数组的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:+ PHP中数组的运算符?
基础教程推荐
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01