Check if two arrays have the same values (regardless of value order)

Check if two arrays have the same values (regardless of value order)

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Checking Array Equality Without Nested Loops

Comparing two arrays to determine if they contain identical values, regardless of their order, is a common requirement in data validation and set theory. The naive approach often involves nested iterations or repeated in_array() calls within a foreach loop. While functional for small datasets, this pattern degrades into $O(n^2)$ complexity as the array size grows. A more efficient strategy leverages built-in language features that handle these operations internally in linear time.

Sorting and Comparison

The most straightforward algorithmic improvement is sorting both arrays before comparing them. If two arrays contain the same elements with the same frequencies, sorting them will result in identical sequences. Once sorted, a standard equality check suffices.

In PHP, this can be achieved using sort(). Since you need to preserve the original order of the input arrays if further processing is required later, create copies first. This ensures the comparison does not mutate the source data.

function haveSameValues(array $array1, array $array2): bool {
    // Create copies to avoid mutating the original arrays
    $copy1 = $array1;
    $copy2 = $array2;

    sort($copy1);
    sort($copy2);

    return $copy1 === $copy2;
}

$result = haveSameValues([2, 5, 3], [5, 2, 3]); // true

This approach reduces complexity to $O(n \log n)$ due to the sorting algorithm. It is robust and handles duplicates correctly because sort() maintains element counts. For example, comparing [1, 1, 2] with [1, 2, 2] will correctly return false, whereas a naive set-based approach might incorrectly return true if it ignored multiplicity.

Using Array Counting for Linear Time

If you prefer an $O(n)$ solution or are dealing with associative arrays where keys matter differently, sorting is no longer the optimal path. Instead, you can normalize the data structure by counting occurrences of each value.

In modern PHP versions (7.3+), array_count_values() provides a concise way to generate a frequency map. By converting both input arrays into these maps and comparing the resulting associative arrays, you achieve an efficient comparison without sorting overhead.

function haveSameValuesCounting(array $array1, array $array2): bool {
    if (count($array1) !== count($array2)) {
        return false; // Quick fail for size mismatch
    }

    $map1 = array_count_values($array1);
    $map2 = array_count_values($array2);

    return $map1 === $map2;
}

This method is particularly effective when the arrays contain integers or strings, as array_count_values handles them seamlessly. If one array contains mixed types that cannot be counted by this function, you might need to cast elements to a common type or use array_unique() combined with counts, though array_count_values remains the standard for homogeneous data.

Trade-offs and Edge Cases

While both methods are significantly faster than nested loops, they come with specific constraints. Sorting modifies the internal order of the arrays you pass to it unless you clone them explicitly. In high-performance scenarios where cloning large datasets is expensive, this memory overhead might be a concern. Conversely, the counting approach relies on the ability to hash values efficiently; while PHP handles this well for standard types, custom objects or complex structures might require a different strategy involving spl_object_hash.

Another pitfall is assuming that simple equality checks cover all cases. If you are working with floating-point numbers, direct comparison after sorting or counting can be risky due to precision errors, though this is less common in typical array manipulation tasks compared to mathematical calculations. Always ensure your environment's PHP version supports the functions used; for instance, array_count_values has been available since PHP 4.3.0, so it is widely compatible, but newer features like match() or specific iterator extensions should be checked before adoption.

For developers working within the Laravel ecosystem, utility methods often wrap these native functions to provide cleaner syntax or additional validation steps. While you can implement this logic directly as shown, leveraging existing packages or helper libraries from trusted sources like LaravelCompany can sometimes offer pre-built solutions tailored for specific application needs, reducing boilerplate code in your controllers or services.

Our network