php: check if an array has duplicates

前端 未结 15 2430
情深已故
情深已故 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:54

    Here's my take on this… after some benchmarking, I found this to be the fastest method for this.

    function has_duplicates( $array ) {
        return count( array_keys( array_flip( $array ) ) ) !== count( $array );
    }
    

    …or depending on circumstances this could be marginally faster.

    function has_duplicates( $array ) {
        $array = array_count_values( $array );
        rsort( $array );
        return $array[0] > 1;
    }
    

提交回复
热议问题