Search code examples
phparraysduplicatesfilteringcase-insensitive

Return only duplicated entries from an array (case-insensitive)


I want to retrieve all case-insensitive duplicate entries from an array. Is this possible in PHP?

array(
    1 => '1233',
    2 => '12334',
    3 => 'Hello',
    4 => 'hello',
    5 => 'U'
);

Desired output array:

array(
    1 => 'Hello',
    2 => 'hello'
);

Solution

  • You will need to make your function case insensitive to get the "Hello" => "hello" result you are looking for, try this method:

    $arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');
    
    // Convert every value to uppercase, and remove duplicate values
    $withoutDuplicates = array_unique(array_map("strtoupper", $arr));
    
    // The difference in the original array, and the $withoutDuplicates array
    // will be the duplicate values
    $duplicates = array_diff($arr, $withoutDuplicates);
    print_r($duplicates);
    

    Output is:

    Array
    (
    [3] => Hello
    [4] => hello
    )
    

    Edit by @AlixAxel:

    This answer is very misleading. It only works in this specific condition. This counter-example:

    $arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'HELLO', 5=>'U');
    

    Fails miserably. Also, this is not the way to keep duplicates:

    array_diff($arr, array_unique($arr));
    

    Since one of the duplicated values will be in array_unique, and then chopped off by array_diff.

    Edit by @RyanDay:

    So look at @Srikanth's or @Bucabay's answer, which work for all cases (look for case insensitive in Bucabay's), not just the test data specified in the question.