Search code examples
phparraysduplicateskeygrouping

Get all array keys where their value occurs more than once in the array


How can I populate an array of two or more keys that share the same value.

For example this is array:

Array
(
   [869] => 87
   [938] => 89
   [870] => 127
   [871] => 127
   [940] => 127
   [942] => 123
   [947] => 123
   [949] => 75
)

Values 87, 89, and 75 only exist once, so they are excluded from the result.

Values that occur more than once should have their keys grouped into subarrays in the result.

Desired result:

Array
(
    [1] => array
    (
        [1] => 870
        [2] => 871
        [3] => 940
    )
    [2] => array
    (
        [1] => 942
        [2] => 947
    )
)

Solution

  • Here is a function that will do what you want. Many not be the simplest it could be but it works:

    <?php
    
    $myArray = array(
       869 => 87,
       938 => 89,
       870 => 127,
       871 => 127,
       940 => 127,
       942 => 123,
       947 => 123,
       949 => 75
    );
    $newArray = $foundKeys = array();
    $itt = 0;
    foreach($myArray as $i => $x){
        foreach($myArray as $j => $y ){
            if($i != $j && !in_array($i,$foundKeys) && $x == $y){
               if(!is_array($newArray[$itt])){
                   $newArray[$itt] = array($i);
               }
               array_push($newArray[$itt],$j);
               array_push($foundKeys,$j);
            }
        }
        $itt++;
    }
    print_r($newArray);
    

    results in:

    Array
    (
        [2] => Array
            (
                [0] => 870
                [1] => 871
                [2] => 940
            )
    
        [5] => Array
            (
                [0] => 942
                [1] => 947
            )
    
    )