Count number of values in array with a given value

Count number of values in array with a given value

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Efficiently Counting Specific Values in PHP Arrays

When you have a collection of data, knowing how many items match a specific criterion is a fundamental operation. Consider an array populated with empty strings and some valid content:

$array = ['', '', 'other', '', 'other'];

The goal is to determine that there are exactly three empty values. A common first instinct for developers is to iterate manually. The source code provided demonstrates this approach using a standard for loop combined with the count() function to manage index bounds:

function without($array) {
    $counter = 0;
    for ($i = 0, $e = count($array); $i < $e; $i++) {
        if (empty($array[$i])) {
            $counter += 1;
        }
    }
    return $counter;
}

While this logic is correct, the performance implications become apparent when scaling up. If you are processing about a dozen arrays containing hundreds of elements each, this manual iteration might take longer than necessary. In specific scenarios described in the source material, such implementations can exceed 30 seconds to complete, suggesting that the overhead or environment constraints are causing significant delays rather than the logic itself being inherently slow. However, the primary lesson here is that relying on a basic for loop for simple counting tasks often ignores more optimized built-in tools available in PHP.

The most efficient and idiomatic solution in modern PHP is to leverage the array_filter() function combined with count(). This approach delegates the iteration logic to the engine, which is highly optimized at the C level. You can filter the array based on a callback that returns true for empty values:

function countEmptyValues($array) {
    return count(array_filter($array, fn($val) => $val === ''));
}

This function explicitly checks for strict equality to an empty string (''). This distinction is critical. The empty() superglobal used in the original loop returns true not only for an empty string but also for zero, false, null, and other falsy values. If your requirement is strictly counting blank strings, using empty() could lead to incorrect counts if the data contains numeric zeros or boolean false values that you intend to exclude. By switching to strict comparison (=== ''), you ensure precision in what constitutes a "blank" value.

Alternatively, if you are working within the Laravel ecosystem, there is a built-in helper that simplifies this further. You can utilize collect() to turn your array into an Eloquent collection and use the count() method with a closure:

$count = collect($array)->where(fn($val) => $val === '')->count();

This syntax is often more readable than manual loops or chaining array functions. It abstracts the iteration away from you, allowing you to focus on the condition. If you are dealing with complex data structures where performance is paramount across many datasets, this functional approach usually offers a cleaner abstraction without sacrificing readability.

Ultimately, the decision between a manual loop and built-in functions comes down to maintainability and correctness. Manual loops offer fine-grained control but require you to handle edge cases like index boundaries and variable length arrays explicitly. Built-in functions like array_filter or Laravel's collection helpers are generally faster because they run on native code rather than interpreted PHP, and they reduce the surface area for bugs. When scaling applications, always prefer the standard library solutions that align with your specific value requirements until you hit a genuine performance bottleneck that requires manual optimization.

Our network