PHP compare array PHP compare array php php

PHP compare array


if ( $a == $b ) {    echo 'We are the same!';}


Comparing two arrays to have equal values (duplicated or not, type-juggling taking into account) can be done by using array_diff() into both directions:

!array_diff($a, $b) && !array_diff($b, $a);

This gives TRUE if both arrays have the same values (after type-juggling). FALSE otherwise. Examples:

function array_equal_values(array $a, array $b) {    return !array_diff($a, $b) && !array_diff($b, $a);}array_equal_values([1], []);            # FALSEarray_equal_values([], [1]);            # FALSEarray_equal_values(['1'], [1]);         # TRUEarray_equal_values(['1'], [1, 1, '1']); # TRUE

As this example shows, array_diff leaves array keys out of the equation and does not care about the order of values either and neither about if values are duplicated or not.


If duplication has to make a difference, this becomes more tricky. As far as "simple" values are concerned (only string and integer values work), array_count_values() comes into play to gather information about which value is how often inside an array. This information can be easily compared with ==:

array_count_values($a) == array_count_values($b);

This gives TRUE if both arrays have the same values (after type-juggling) for the same amount of time. FALSE otherwise. Examples:

function array_equal_values(array $a, array $b) {    return array_count_values($a) == array_count_values($b);}array_equal_values([2, 1], [1, 2]);           # TRUEarray_equal_values([2, 1, 2], [1, 2, 2]);     # TRUEarray_equal_values(['2', '2'], [2, '2.0']);   # FALSEarray_equal_values(['2.0', '2'], [2, '2.0']); # TRUE

This can be further optimized by comparing the count of the two arrays first which is relatively cheap and a quick test to tell most arrays apart when counting value duplication makes a difference.


These examples so far are partially limited to string and integer values and no strict comparison is possible with array_diff either. More dedicated for strict comparison is array_search. So values need to be counted and indexed so that they can be compared as just turning them into a key (as array_search does) won't make it.

This is a bit more work. However in the end the comparison is the same as earlier:

$count($a) == $count($b);

It's just $count that makes the difference:

    $table = [];    $count = function (array $array) use (&$table) {        $exit   = (bool)$table;        $result = [];        foreach ($array as $value) {            $key = array_search($value, $table, true);            if (FALSE !== $key) {                if (!isset($result[$key])) {                    $result[$key] = 1;                } else {                    $result[$key]++;                }                continue;            }            if ($exit) {                break;            }            $key          = count($table);            $table[$key]  = $value;            $result[$key] = 1;        }        return $result;    };

This keeps a table of values so that both arrays can use the same index. Also it's possible to exit early the first time in the second array a new value is experienced.

This function can also add the strict context by having an additional parameter. And by adding another additional parameter would then allow to enable looking for duplicates or not. The full example:

function array_equal_values(array $a, array $b, $strict = FALSE, $allow_duplicate_values = TRUE) {    $add = (int)!$allow_duplicate_values;    if ($add and count($a) !== count($b)) {        return FALSE;    }    $table = [];    $count = function (array $array) use (&$table, $add, $strict) {        $exit   = (bool)$table;        $result = [];        foreach ($array as $value) {            $key = array_search($value, $table, $strict);            if (FALSE !== $key) {                if (!isset($result[$key])) {                    $result[$key] = 1;                } else {                    $result[$key] += $add;                }                continue;            }            if ($exit) {                break;            }            $key          = count($table);            $table[$key]  = $value;            $result[$key] = 1;        }        return $result;    };    return $count($a) == $count($b);}

Usage Examples:

array_equal_values(['2.0', '2', 2], ['2', '2.0', 2], TRUE);           # TRUEarray_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE);        # TRUEarray_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE, FALSE); # FALSEarray_equal_values(['2'], ['2'], TRUE, FALSE);                        # TRUEarray_equal_values([2], ['2', 2]);                                    # TRUEarray_equal_values([2], ['2', 2], FALSE);                             # TRUEarray_equal_values([2], ['2', 2], FALSE, TRUE);                       # FALSE


@Cleanshooter i'm sorry but this does not do, what it is expected todo: (so does array_diff mentioned in this context)

$a1 = array('one','two');$a2 = array('one','two','three');var_dump(count(array_diff($a1, $a2)) === 0); // returns TRUE

(annotation: you cannot use empty on functions before PHP 5.5)in this case the result is true allthough the arrays are different.

array_diff [...] Returns an array containing all the entries from array1 that are not present in any of the other arrays.

which does not mean that array_diff is something like: array_get_all_differences. Explained in mathematical sets it computes:

{'one','two'} \ {'one','two','three'} = {}

which means something like all elements from first set without all the elements from second set, which are in the first set.So that

var_dump(array_diff($a2, $a1));

computes to

array(1) { [2]=> string(5) "three" } 

The conclusion is, that you have to do an array_diff in "both ways" to get all "differences" from the two arrays.

hope this helps :)