Check if two arrays values are equal in PHP
Snippet
1) Comparing arrays using strict equality (===)
Two arrays are strict equal ($a === $b
) when:
- they have the same key/value pairs
- the key/values are in the same order
- the values ar e of the same types
2) Comparing arrays using loose equality (==)
Two arrays are loose equal ($a == $b
) when they have the same key/value pairs
Examples of comparing 1 and 2 arrays
<?php
$a = ['a', 'b'];
$b = ['a', 'b'];
var_dump($a == $b); // true
var_dump($a === $b); // true
$a = ['a', 'b'];
$b = [0 => 'a', 1 => 'b'];
var_dump($a == $b); // true
var_dump($a === $b); // true
Associative arrays:
<?php
$a = ['a', 'b', [ 'foo' => 'bar' ]];
$b = ['a', 'b', [ 'foo' => 'bar' ]];
var_dump($a == $b); // true
var_dump($a === $b); // true
$a = ['a', 'b', [ 'foo' => 'bar' ]];
$b = [0 => 'a', 1 => 'b', 3 => [ 'foo' => 'bar' ]];
var_dump($a == $b); // true
var_dump($a === $b); // true
<?php
$a = [0 => 'a', 1 => 'b', 2 => 'c'];
$b = [false => 'a', true => 'b', '2' => 'c'];
var_dump($a == $b); // true
var_dump($a === $b); // true
<?php
$a = ['a', 'b'];
$b = ['b', 'a'];
var_dump($a == $b); // false
var_dump($a === $b); // false
$a = [0 => 'a', 1 => 'b'];
$b = [0 => 'b', 1 => 'a'];
var_dump($a == $b); // false
var_dump($a === $b); // false
Associative arrays:
<?php
$a = [1 => 'a', 2 => 'b', [ 'foo' => 'bar' ]];
$b = [[ 'foo' => 'bar' ], 2 => 'b', 1 => 'a'];
var_dump($a == $b); // false
var_dump($a === $b); // false
$a = [1 => 'a', 2 => 'b', 3 => [ 'foo' => 'bar' ]];
$b = [0 => [ 'foo' => 'bar' ], 2 => 'b', 1 => 'a'];
var_dump($a == $b); // false
var_dump($a === $b); // false
<?php
$a = [1, 2, 3];
$b = ['1', 2, 3];
var_dump($a == $b); // true
var_dump($a === $b); // false
$a = [false, true];
$b = [0, 3];
var_dump($a == $b); // true
var_dump($a === $b); // false
<?php
$a = [1 => 'a', 2 => 'b'];
$b = [2 => 'b', 1 => 'a'];
var_dump($a == $b); // true
var_dump($a === $b); // false
But it will not work as expected with indexed arrays
<?php
$a = [0 => 'a', 1 => 'b'];
$b = [0 => 'b', 1 => 'a'];
var_dump($a == $b); // false
var_dump($a === $b); // false
To solve that issue, use:
<?php
function arrayEqual($a, $b) {
return (
is_array($a)
&& is_array($b)
&& count($a) == count($b)
&& array_diff($a, $b) === array_diff($b, $a)
);
}
$a = [0 => 'a', 1 => 'b'];
$b = [0 => 'b', 1 => 'a'];
var_dump(arrayEqual($a, $b)); // true