skip to Main Content

I have an array that contains duplicate IDs, which need to be extracted, but only if there is a total equal to X.

X will vary and would need to be set as a variable in the function.

In this example, X is equal to 3;

Array
(
    [0] => 189
    [1] => 185
    [2] => 188
    [3] => 178
    [4] => 189
    [5] => 190
    [6] => 185
    [7] => 186
    [8] => 191
    [9] => 188
    [10] => 187
    [11] => 180
    [12] => 182
    [13] => 181
    [14] => 183
    [15] => 184
    [16] => 177
    [17] => 178
    [18] => 189
    [19] => 185
    [20] => 188
    [21] => 180
    [22] => 178
)

As such, the extracted result should be;

Array
(
    [1] => 178
    [2] => 185
    [3] => 188
)

Is there a simple loop or PHP function to handle this type of data extraction?

Many thanks!

3

Answers


  1. You can use array_count_values to get the count of the values. Then use array_filter with a custom call back to return the duplicates.

    Then a simple for each to find and unset values in the array that are less than your passed value.

    Last just return the array_keys from the array.

    $array = [189,185,188,178,189,190,185,186,191,188,187,180,182,181,183,184177,178,189,185,188,180,178];
    
    function justDupes($dupeCount, $array){
        $r = array_filter(array_count_values($array), function($v) { return $v > 1; });
        foreach($r as $k => $v){
            if($v < $dupeCount){
                unset($r[$k]);
            }
        }
        return array_keys($r);
    }
    
    print_r(justDupes(3, $array));
    
    Login or Signup to reply.
  2. $input = [
      189,
      185,
      188,
      178,
      189,
      190,
      185,
      186,
      191,
      188,
      187,
      180,
      182,
      181,
      183,
      184,
      177,
      178,
      189,
      185,
      188,
      180,
      178
    ];
    
    $x = 3;
    
    $result = array_keys(
      array_filter(
        array_count_values($input),
        static fn(int $count): bool => $count === $x
      )
    );
    
    Login or Signup to reply.
  3. You could use array_count_values()

    Here is the solution, and actually you have four values that are duplicated 3 times and not three.

    <?php
    
    $x = 3;
    
    $data = array(
    189, 185, 188, 178, 189, 190, 185, 186, 191, 188, 187, 180, 182, 181, 183, 184, 177, 178, 189, 185, 188, 180, 178
    );
    
    echo '<pre>';
    print_r(extract_duplicated_values($data,$x));
    
    
    
    //Function description
    function extract_duplicated_values($data, $x)
    {
    $count = array_count_values($data);
    $output = [];
    foreach ($count as $key => $value) {
        if ($value == $x) {
            $output[] = $key;
        }
    }
    return $output;
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search