我有一些代码,似乎使用+=合并来自两个数组的数据,但它不包括元素中的所有元素。它是如何工作的?

例子:

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

输出:

array(2) {
  [0]=>
  string(2) "hi"
  [1]=>
  string(2) "oh"
}

在PHP数组中使用+是什么意思?


当前回答

从https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/

也就是说,我们可以认为+运算符有点多余,因为array_replace函数也可以实现同样的效果。 然而,在有些情况下,它派上用场:假设你有一个$options数组被传递给一个函数/方法,也有默认值用作备用:

// we could do it like this
function foo(array $options)
{
   $defaults = ['foo' => 'bar'];
   
   $options = array_replace($defaults, $options);
 
   // ...
}
 
// but + here might be way better:
function foo(array $options)
{
   $options += ['foo' => 'bar'];
 
   // ...
}

其他回答

该运算符接受两个数组的并集(与array_merge相同,只是使用array_merge时重复的键会被覆盖)。

数组操作符的文档可以在这里找到。

它将把新数组附加到前一个数组。

我发现最好的例子是在配置数组中。

$user_vars = array("username"=>"John Doe");
$default_vars = array("username"=>"Unknown", "email"=>"no-reply@domain.com");

$config = $user_vars + $default_vars;

如它所示,$default_vars是默认值的数组。 $user_vars数组将覆盖$default_vars中定义的值。 $user_vars中的任何缺失值现在都是$default_vars中的默认值。

这将把print_r打印为:

Array(2){
    "username" => "John Doe",
    "email" => "no-reply@domain.com"
}

我希望这能有所帮助!

从https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/

也就是说,我们可以认为+运算符有点多余,因为array_replace函数也可以实现同样的效果。 然而,在有些情况下,它派上用场:假设你有一个$options数组被传递给一个函数/方法,也有默认值用作备用:

// we could do it like this
function foo(array $options)
{
   $defaults = ['foo' => 'bar'];
   
   $options = array_replace($defaults, $options);
 
   // ...
}
 
// but + here might be way better:
function foo(array $options)
{
   $options += ['foo' => 'bar'];
 
   // ...
}
$var1 = "example";
$var2 = "test";
$output = array_merge((array)$var1,(array)$var2);
print_r($output);

数组([0]=> example [1] => test)