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?