Check and return duplicates array php

前端 未结 10 2129
我寻月下人不归
我寻月下人不归 2020-12-05 22:33

I would like to check if my array has any duplicates and return the duplicated values in an array. I want this to be as efficient as possible.

Example:



        
10条回答
  •  感动是毒
    2020-12-05 23:19

    If you need a solution that will work with an array of arrays (or any array values other than integers or strings) try this:

    function return_dup( $arr ) {
        $dups = array();
        $temp = $arr;
        foreach ( $arr as $key => $item ) {
            unset( $temp[$key] );
            if ( in_array( $item, $temp ) ) {
                $dups[] = $item;
            }
        }
        return $dups;
    }
    
    
    $arr = array(
        array(
            0 => 'A',
            1 => 'B',
        ),
        array(
            0 => 'A',
            1 => 'B',
        ),
        array(
            0 => 'C',
            1 => 'D',
        ),
        array(
            0 => 'C',
            1 => 'D',
        ),
        array(
            0 => 'E',
            1 => 'F',
        ),
        array(
            0 => 'F',
            1 => 'E',
        ),
        array(
            0 => 'Y',
            1 => 'Z',
        ),
    );
    
    var_export( return_dup( $arr ) );
    /*
    array (
        0 => array (
            0 => 'A',
            1 => 'B',
        ),
        1 => array (
            0 => 'C',
            1 => 'D',
        ),
    )
    */
    

提交回复
热议问题