php: check if an array has duplicates

前端 未结 15 2292
情深已故
情深已故 2020-11-27 04:07

I\'m sure this is an extremely obvious question, and that there\'s a function that does exactly this, but I can\'t seem to find it. In PHP, I\'d like to know if my array has

相关标签:
15条回答
  • 2020-11-27 04:41

    Two ways to do it efficiently that I can think of:

    1. inserting all the values into some sort of hashtable and checking whether the value you're inserting is already in it(expected O(n) time and O(n) space)

    2. sorting the array and then checking whether adjacent cells are equal( O(nlogn) time and O(1) or O(n) space depending on the sorting algorithm)

    stormdrain's solution would probably be O(n^2), as would any solution which involves scanning the array for each element searching for a duplicate

    0 讨论(0)
  • 2020-11-27 04:42
    $hasDuplicates = count($array) > count(array_unique($array)); 
    

    Will be true if duplicates, or false if no duplicates.

    0 讨论(0)
  • 2020-11-27 04:42

    Php has an function to count the occurrences in the array http://www.php.net/manual/en/function.array-count-values.php

    0 讨论(0)
  • 2020-11-27 04:43

    Find this useful solution

    function get_duplicates( $array ) {
        return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
    }
    

    After that count result if greater than 0 than duplicates else unique.

    0 讨论(0)
  • 2020-11-27 04:45

    I know you are not after array_unique(). However, you will not find a magical obvious function nor will writing one be faster than making use of the native functions.

    I propose:

    function array_has_dupes($array) {
       // streamline per @Felix
       return count($array) !== count(array_unique($array));
    }
    

    Adjust the second parameter of array_unique() to meet your comparison needs.

    0 讨论(0)
  • 2020-11-27 04:45

    I'm using this:

    if(count($array)==count(array_count_values($array))){
        echo("all values are unique");
    }else{
        echo("there's dupe values");
    }
    

    I don't know if it's the fastest but works pretty good so far

    0 讨论(0)
提交回复
热议问题