Ivar
Ivar

Reputation: 796

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

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.

Upvotes: 4

Views: 1272

Answers (2)

Lautaro Orazi
Lautaro Orazi

Reputation: 166

array_count_values

Upvotes: 3

animuson
animuson

Reputation: 54719

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)

Upvotes: 8

Related Questions