How to count the duplicate values in an array with PHP

3 Answers

0 votes
$arr = array(1,1,1,1,2,3,3,1,2,1,2,2,3,3,4,3);

$result = array_fill_keys(array(1, 2, 3, 4), '');

foreach ($arr as $val) {
    $result[$val]++;
}

print_r($result);




/*
run:

Array
(
    [1] => 6
    [2] => 4
    [3] => 5
    [4] => 1
)

*/

 



answered Jul 12, 2023 by avibootz
0 votes
$arr = array(1,1,1,1,2,3,3,1,2,1,2,2,3,3,4,3);

$result = array(0, 0, 0, 0, 0);

foreach ($arr as $val) {
    $result[$val]++;
}

print_r($result);




/*
run:

Array
(
    [0] => 0
    [1] => 6
    [2] => 4
    [3] => 5
    [4] => 1
)

*/

 



answered Jul 12, 2023 by avibootz
0 votes
$arr = array(1,1,1,1,2,3,3,1,2,1,2,2,3,3,4,3);

$countedValues = array_count_values($arr); 
 
foreach ($countedValues as $key => $value) { 
    if ($value > 1) { 
        echo "$key appears $value times\n"; 
    } 
} 





/*
run:

1 appears 6 times
2 appears 4 times
3 appears 5 times

*/

 



answered Jul 12, 2023 by avibootz

Related questions

1 answer 262 views
5 answers 664 views
1 answer 278 views
1 answer 269 views
1 answer 295 views
2 answers 379 views
...