Home > Back-end >  php check for duplicates and count the number of occurrences in the array
php check for duplicates and count the number of occurrences in the array

Time:07-16

For a given array of number I need to print the duplicates along with the number of time they occurred in the array in the key value pair or associative array.

Given Array

$arr = [1,2,2,2,4,5,5,5,8,9,10,2,5,9,10,10];

Desired result

Array
(
    [2] => 4
    [5] => 4
    [9] => 2
    [10] => 3
)

What I have tried:

$arr = [1,2,2,2,4,5,5,5,8,9,10,2,5,9,10,10];
sort($arr);

$duplicates = [];
$count = 1; // I assumed that at least one element is always there so I did not take 0 (if I am not wrong)

for($i = 0; $i<count($arr); $i  ){  
  for($j = $i 1; $j<count($arr); $j  ){
    if($arr[$i] == $arr[$j]){  
      if(!in_array($arr[$j], $duplicates)){
        // array_push($duplicates, $arr[$j]);
        $count  ;
        $duplicates[$arr[$j]] = $count;
      }
    }else{
      $count = 1;
    }
  }
}

echo "<pre>";
print_r($duplicates);

This successfully returns the duplicates as key but number of occurrences are incorrect.

Current Output

Array
(
    [2] => 2
    [5] => 2
    [9] => 2
    [10] => 4
)

What mistake am I making? Is my logic incorrect?

CodePudding user response:

If you consider the time complexity of your solution, it's not very efficient apart from logical error. Here is a solution that works:

<?php
function solution($arr) {
    $result =   array();
    $i = 0;
    /* Increase count for each numbers */
    while( $i < count($arr) ) {
        $current = $arr[$i];
        if ( !array_key_exists("$current", $result) ) {
            $result["$current"] = 1;
        } else {
            $result["$current"]  = 1;
        }
        $i  ;
    }

    /* Remove values less than 2 */
    foreach ( $result as $k => $res ) {
        if ( $res < 2 ) {
            unset($result[$k]);
        }
    }

    echo json_encode($result);
}

solution([1,2,2,2,4,5,5,5,8,9,10,2,5,9,10,10]);
?>

Output:

{"2":4,"5":4,"9":2,"10":3}

Hopefully, this helps! Good luck!

CodePudding user response:

your answer:

$duplicates = array_diff( array_count_values($arr), [...NUMBER_OF_REPETITUS_YOU_WONT] );

You don't need to use loops, but assuming you do, you can use optimal ways of doing what you've done.

$duplicates = [];
foreach( $arr as $item ){
    ( array_key_exists($item, $duplicates) )?
        $duplicates[$item]  :
        $duplicates[$item] = 1;
}

CodePudding user response:

I prefer isset() instead of array_key_exists() (as suggested by babak-maziar).

$arr = [1,2,2,2,4,5,5,5,8,9,10,2,5,9,10,10];

foreach($arr as $i)
    isset($counters[$i])
        ? $counters[$i]  
        : $counters[$i] = 1;

var_export($counters);

output:

array (
  1 => 1,
  2 => 4,
  4 => 1,
  5 => 4,
  8 => 1,
  9 => 2,
  10 => 3,
)%
  • Related