+ operator for array in PHP?
This operator takes the union of two arrays (same as array_merge, except that with array_merge duplicate keys are overwritten).
The documentation for array operators is found here.
Quoting from the 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.
So if you do
$array1 = ['one', 'two', 'foo' => 'bar'];
$array2 = ['three', 'four', 'five', 'foo' => 'baz'];
print_r($array1 + $array2);
You will get
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;
}
}
If you are interested in the details of the C-level implementation head to
- php-src/Zend/zend_operators.c
Note, that +
is different from how array_merge()
would combine the arrays:
print_r(array_merge($array1, $array2));
would give you
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.
The best example I found for using this is in a config array.
$user_vars = array("username"=>"John Doe");
$default_vars = array("username"=>"Unknown", "email"=>"[email protected]");
$config = $user_vars + $default_vars;
The $default_vars
, as it suggests, is the array for default values.
The $user_vars
array will overwrite the values defined in $default_vars
.
Any missing values in $user_vars
are now the defaults vars from $default_vars
.
This would print_r
as:
Array(2){
"username" => "John Doe",
"email" => "[email protected]"
}
I hope this helps!