Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Operators

PHP array operators

Reference for PHP array operators: union with +, equality ==, identity ===, inequality and <=> comparison, with key and order rules and gotchas.

PHP gives arrays a small set of operators. + builds a union: it keeps all keys of the left array and adds only the keys from the right array that the left one does not have. == and === compare arrays, and !=, <> and !== are their opposites.

The union operator is easy to confuse with array_merge(). They differ for keys that exist in both arrays and for integer keys.

PHP
$defaults = ["color" => "blue", "size" => "M"];
$options = ["color" => "red"] + $defaults;

Try it

PHP Union with +

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Equality versus identity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
$a + $b      $a == $b     $a === $b
$a != $b     $a <> $b     $a !== $b
Operator Result
$a + $b Union: keys of $a, plus keys of $b that are missing in $a
$a == $b true if both have the same key/value pairs (values compared loosely)
$a === $b true if same pairs, same order and same types
$a != $b, $a <> $b true if not ==
$a !== $b true if not ===

Errors: + between an array and a non-array throws TypeError ("Unsupported operand types").

Usage notes

  • Left wins. In a union the left array's value is kept for duplicate keys, so $userOptions + $defaults is a neat way to apply defaults.
  • Integer keys are not renumbered. [1, 2] + [10, 20, 30] keeps [1, 2, 30]: keys 0 and 1 already exist. array_merge() renumbers integer keys and appends instead, and for string keys the later value wins.
  • == ignores order, === does not. Both check that the key sets match.
  • Comparing with <, > and <=> compares the count first, then values key by key. This is handy for sorting with several criteria.
  • Nested arrays are compared recursively. Objects inside use their own comparison rules.
  • Large recursion. Comparing arrays that contain themselves can raise a fatal "Nesting level too deep" error.
  • array_replace() is the function form of "right wins" for the same keys.