A few operators work on whole arrays.
| Operator | Name | Result |
|---|---|---|
$a + $b | Union | Items of $a, plus items of $b whose keys are missing from $a |
$a == $b | Equality | Same key/value pairs |
$a === $b | Identity | Same pairs, same order, same types |
$a != $b or $a <> $b | Inequality | Not equal |
$a !== $b | Non-identity | Not identical |
Union: +
<?php
$defaults = ["theme" => "light", "lang" => "en"];
$custom = ["theme" => "dark"];
$settings = $custom + $defaults;
print_r($settings);
Array
(
[theme] => dark
[lang] => en
)
Keys from the left array win. $defaults only fills in what $custom lacks. That makes + a neat way to apply defaults.
The numeric key trap
For indexed arrays the keys are 0, 1, 2. Union keeps the left items at those keys and ignores the right items with the same keys.
<?php
$a = ["a", "b"];
$b = ["x", "y", "z"];
print_r($a + $b);
Array
(
[0] => a
[1] => b
[2] => z
)
If you want to join two lists, use array_merge() or the spread operator instead. See Common Array Functions.
<?php
print_r(array_merge(["a", "b"], ["x", "y", "z"]));
Array
(
[0] => a
[1] => b
[2] => x
[3] => y
[4] => z
)
Equality and identity
<?php
$one = ["a" => 1, "b" => 2];
$two = ["b" => 2, "a" => 1];
$three = ["a" => "1", "b" => 2];
var_dump($one == $two); // same pairs, order ignored
var_dump($one === $two); // order differs
var_dump($one == $three); // 1 == "1"
var_dump($one === $three); // types differ
bool(true)
bool(false)
bool(true)
bool(false)
Pick by intent
+. Want “put these lists together”? Use array_merge() or [...$a, ...$b].