+ operator for array in PHP?
对于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.
所以如果你这样做
1 2 3 4 | $array1 = ['one', 'two', 'foo' => 'bar']; $array2 = ['three', 'four', 'five', 'foo' => 'baz']; print_r($array1 + $array2); |
你会得到
1 2 3 4 5 6 7 | 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) ) |
因此,
1 2 3 4 5 6 7 | $union = $array1; foreach ($array2 as $key => $value) { if (false === array_key_exists($key, $union)) { $union[$key] = $value; } } |
如果您对C级实现的细节感兴趣,请访问
- php-src/zend/zend_operators.c
注意,
1 |
会给你
1 2 3 4 5 6 7 8 9 | 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 ) |
有关更多示例,请参见链接页。
我发现使用它的最佳示例是在配置数组中。
1 2 3 4 | $user_vars = array("username"=>"John Doe"); $default_vars = array("username"=>"Unknown","email"=>"[email protected]"); $config = $user_vars + $default_vars; |
顾名思义,
这将使cx1〔8〕成为:
1 2 3 4 |
希望这有帮助!
此运算符接受两个数组的并集(与"数组合并"相同,但"数组合并"的重复键将被覆盖)。
在这里可以找到数组运算符的文档。
如果需要保留数字键或不想释放任何内容,请谨慎使用数字键
联盟
合并
1 2 3 4 5 6 7 8 9 10 |
在此页面的另一个示例上展开:
1 2 3 4 5 |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Array ( [0] => one // preserved from $array1 [1] => two // preserved from $array1 [foo] => bar // preserved from $array1 [2] => five // added from $array2 ) Array ( [0] => one // preserved from $array1 [1] => two // preserved from $array1 [2] => five // added from $array2 [foo] => bar // preserved from $array1 ) |
Array plus operation treats all array as assoc array. When key conflict during plus, left(previous) value will be kept
我发布下面的代码以使事情清楚。
1 2 3 4 5 6 |
它将把新数组追加到前一个数组。
1 2 3 4 | $var1 ="example"; $var2 ="test"; $output = array_merge((array)$var1,(array)$var2); print_r($output); |
数组([0]=>示例[1]=>测试)