Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP compare array

People also ask

How do I check if two arrays are equal in PHP?

Use php function array_diff(array1, array2); It will return a the difference between arrays. If its empty then they're equal.

How can I find matching values in two arrays PHP?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

How do you compare values in an array?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do you compare if 2 arrays are equal to each other?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


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], []);            # FALSE
array_equal_values([], [1]);            # FALSE
array_equal_values(['1'], [1]);         # TRUE
array_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]);           # TRUE
array_equal_values([2, 1, 2], [1, 2, 2]);     # TRUE
array_equal_values(['2', '2'], [2, '2.0']);   # FALSE
array_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);           # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE);        # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE, FALSE); # FALSE
array_equal_values(['2'], ['2'], TRUE, FALSE);                        # TRUE
array_equal_values([2], ['2', 2]);                                    # TRUE
array_equal_values([2], ['2', 2], FALSE);                             # TRUE
array_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 :)


Also you can try this way:

if(serialize($a1) == serialize($a2))

Just check $a1 == $a2 -- what's wrong with that?


array_intersect() returns an array containing all the common values.