Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function to count the number of times a value occurs within an array?

Tags:

arrays

php

I need to count the number of times a value occurs in a given array.

For example:

$array = array(5, 5, 2, 1);

// 5 = 2 times
// 2 = 1 time
// 1 = 1 time

Does such a function exist? If so, please point me to it in the php docs... because I can't seem to find it.

Thanks.

like image 399
Ivar Avatar asked Dec 22 '22 02:12

Ivar


1 Answers

Yes, it's called array_count_values().

$array = array(5, 5, 2, 1);
$counts = array_count_values($array); // Array(5 => 2, 2 => 1, 1 => 1)
like image 200
animuson Avatar answered Dec 24 '22 02:12

animuson