Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how often a particular value appears in an array

Tags:

arrays

php

count

I know the function count() of php, but what's the function for counting how often a value appear in an array?

Example:

$array = array(
  [0] => 'Test',
  [1] => 'Tutorial',
  [2] => 'Video',
  [3] => 'Test',
  [4] => 'Test'
);

Now I want to count how often "Test" appears.

like image 364
Poru Avatar asked Mar 13 '10 00:03

Poru


People also ask

How do you count occurrences of each element in an array in PHP?

array_count_values() function in PHP The array_count_values() function returns an array with the number of occurrences for each value. It returns an associative array. The returned array has keys as the array's values, whereas values as the count of the passed values.


2 Answers

PHP has a function called array_count_values for that.

Example:

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

Output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
like image 185
Wolph Avatar answered Oct 04 '22 05:10

Wolph


Try the function array_count_values you can find more information about the function in the documentation here: http://www.php.net/manual/en/function.array-count-values.php

Example from that page:

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

Will produce:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
like image 21
Tommy Andersen Avatar answered Oct 04 '22 03:10

Tommy Andersen