8

I'm looking for a way to check if two arrays are identical, for example

  $a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);

These two would be identical, but if a single value was changed, it would return false, I know I could write a function, but is there one already built?

Saulius Antanavicius
  • 1,371
  • 6
  • 25
  • 55

2 Answers2

30

You can just use $a == $b if order doesn't matter, or $a === $b if order does matter.

For example:

$a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$c = array(
    '3' => 14,
    '1' => 12,
    '6' => 11
);
$d = array(
    '1' => 11,
    '3' => 14,
    '6' => 11
);

$a == $b;   // evaluates to true
$a === $b;  // evaluates to true
$a == $c;   // evaluates to true
$a === $c;  // evaluates to false
$a == $d;   // evaluates to false
$a === $d;  // evaluates to false
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
15

You can use

$a === $b // or $a == $b

example of usage:

<?php
$a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
echo ($a === $b) ? 'they\'re same' : 'they\'re different';

echo "\n";
$b['1'] = 11;

echo ($a === $b) ? 'they\'re same' : 'they\'re different';

which will return

they're same
they're different

demo

Martin.
  • 10,494
  • 3
  • 42
  • 68
  • This answer is misleading to people coming in from search. `array_diff` does not work very well for checking for "identical arrays." It also has a premise that the keys will not change. Adding another key, with one of the existing values, will not work with array_diff, also adding a value to the first array or the second array gives different results. – Dustin Graham Mar 17 '12 at 18:45
  • @DustinGraham: can you show me a demo of what you mean? I'm a bit confused with this – Martin. Mar 17 '12 at 18:54
  • If a person arrives here looking for a way to tell if two arrays are identical, the answer (yours) has the first suggestion of `array_diff()` which can be misleading, try this: `$a = array('x' => true, 'y' => false); $b = array('x' => true, 'y' => true, 'z' => false); print_r(array_diff($a,$b));` Clearly they are not identical, but `array_diff` shows no differences. – Dustin Graham Mar 17 '12 at 19:46
  • Works for subarrays too. – McGafter Jul 16 '19 at 15:12