Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 0

By a condition

Filter and count:

<?php
 
$numbers = [5, 12, 8, 20, 3];
 
echo count(array_filter($numbers, fn ($n) => $n > 7));

Output:

3

Functions 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.

Thanks for reading!

Donate to the site — we work hard for you.