How to count occurrences of a value in an array
Short answer
array_count_values() counts every value at once:
<?php
echo json_encode(array_count_values(['tea', 'coffee', 'tea', 'tea']));Output:
{"tea":3,"coffee":1}A single value
Take the needed key from the result; if it is missing, substitute zero:
<?php
$counts = array_count_values(['tea', 'coffee', 'tea']);
echo $counts['tea'] ?? 0, ' ', $counts['juice'] ?? 0;Output:
2 0By a condition
Filter and count:
<?php
$numbers = [5, 12, 8, 20, 3];
echo count(array_filter($numbers, fn ($n) => $n > 7));Output:
3Functions used in this recipe
- array_count_values — Counts how many times each value occurs.
- array_filter — Keeps the array elements that pass a test.
- count — Returns the number of elements in an array.