php: check if an array has duplicates

php: check if an array has duplicates

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

Stefan Bogdanescu

Founder & Senior Architect

Efficiently Detecting Duplicates in PHP Arrays Without Modification

In PHP, determining whether an array contains duplicates is a frequent requirement when validating data structures or preparing inputs for downstream processing. Many developers instinctively reach for array_unique(), but this function alters the original array and performs operations that are unnecessary if you only need a boolean check. Removing elements just to see what remains adds overhead, especially if your "expected condition" is that the array is clean.

To avoid modifying the input or performing redundant comparisons, you can leverage PHP's built-in capabilities to count occurrences or utilize type-specific functions depending on your PHP version. The most direct approach relies on array_count_values(). This function returns an associative array where keys are the values from the original array and values represent their frequency. By iterating through this result, you can check if any value appears more than once.

Here is a straightforward implementation:

function has_duplicates($array) {
    $counts = array_count_values($array);
    foreach ($counts as $count) {
        if ($count > 1) {
            return true;
        }
    }
    return false;
}

if (!has_duplicates($array)) {
    // Process clean data
} else {
    // Handle duplicates
}

While effective, this method requires a full pass to build the frequency map and then another pass to inspect it. If performance is critical for very large arrays, you can optimize by returning immediately upon finding the first duplicate. However, if the array is expected to be duplicate-free most of the time, array_count_values() might still perform better than early-exit strategies that scan every element individually, as building the map in one go is often faster than nested loops.

Leveraging Intersection for Cleaner Syntax

A more concise alternative involves using array_intersect(). This function returns a new array containing all elements from the first array that also exist in the second. By intersecting the original array with itself, you effectively isolate every element that appears at least twice. If the resulting intersection is empty, there are no duplicates.

function has_duplicates_intersection($array) {
    return !empty(array_intersect($array, $array));
}

This approach is elegant and readable, but it carries a specific limitation: it treats all duplicate values equally regardless of their position. More importantly, if your array contains mixed types or null values, array_intersect() behavior can sometimes be less intuitive than expected depending on the PHP version and strict typing settings. It also creates a temporary array for the intersection result before checking its emptiness, which adds memory overhead proportional to the number of duplicates found.

Version-Specific Considerations with Typed Arrays

If you are working in an environment that supports typed arrays (PHP 7.4+), there is another efficient strategy using array_count_values() directly on a specific type or utilizing native functions designed for strict comparisons. However, the general consensus remains that checking counts is often more predictable than relying on intersection logic for mixed-type datasets.

When integrating this logic into larger applications, consider where this check fits in your data pipeline. If you are validating user input before storing it in a database, failing fast with a clear error message when duplicates are detected prevents downstream inconsistencies. Conversely, if you are processing logs or temporary buffers, the overhead of these checks might be negligible compared to I/O operations.

For projects built on Laravel, you might find yourself needing this logic within form validation rules or data sanitization middleware. While Laravel does not provide a native helper specifically for duplicate detection in arrays outside of collection methods like isUnique(), implementing a custom closure or helper function as shown above ensures you maintain control over the performance characteristics and avoid unintended side effects on your original data structures.

Ultimately, choosing between array_count_values() and array_intersect() depends on whether you prioritize code brevity or granular control over the counting process. For most scenarios where the array is expected to be clean, the cost of a single pass to count values is a small price to pay for avoiding accidental data mutation.

Our network