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?

3
  • 1
    But if a single value was changed then they wouldn't be identical. What's the question here? Commented Nov 27, 2011 at 3:37
  • 1
    Did you even try just using ===? Commented Nov 27, 2011 at 3:45
  • Possible duplicate of PHP - Check if two arrays are equal Commented Nov 20, 2018 at 9:38

2 Answers 2

31

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
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

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.
@DustinGraham: can you show me a demo of what you mean? I'm a bit confused with this
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.
Works for subarrays too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.