Comparing Arrays in PHP

Array-to-array comparison is a relatively rare occurrence in the real world of PHP (at least for me), but it can be performed using a set of operators. Like for other types, the equivalence and identity operators can be used for this purpose:

  1.  
  2. $a = array (1, 2, 3);
  3. $b = array (1 => 2, 2 => 3, 0 => 1);
  4. $c = array (’a’ => 1, ’b’ => 2, ’c’ => 3);
  5. var_dump ($a == $b); // True
  6. var_dump ($a === $b); // False
  7. var_dump ($a == $c); // False
  8. var_dump ($a === $c); // False
  9.  

As you can see, the equivalence operator == returns true if both arrays have the same number of elements with the same values and keys, regardless of their order. The identity operator ===, on the other hand, returns true only if the array contains the same key/value pairs in the same order.

Similarly, the inequality and non-identity operators can determine whether two arrays are different:

  1.  
  2. $a = array (1, 2, 3);
  3. $b = array (1 => 2, 2 => 3, 0 => 1);
  4. var_dump ($a != $b); // False
  5. var_dump ($a !== $b); // True
  6.  

Once again, the inequality operator only ensures that both arrays contain the same elements with the same keys, whereas the non-identity operator also verifies their position.

Apparently arrays are covered heavily on the Zend PHP Certification Exam so the next few posts will cover arrays.