Home >Backend Development >PHP Tutorial >How Can I Efficiently Count Occurrences of Specific Values in a PHP Array?

How Can I Efficiently Count Occurrences of Specific Values in a PHP Array?

DDD
DDDOriginal
2024-12-01 05:52:11336browse

How Can I Efficiently Count Occurrences of Specific Values in a PHP Array?

Counting Values in an Array Using Array_count_values

When working with arrays, it's often necessary to count the occurrence of specific values. For instance, consider an array containing both blank and non-blank values:

$array = array('', '', 'other', '', 'other');

The goal is to determine the number of blank values in the array efficiently, especially for larger arrays with hundreds of elements.

Initially, we might consider a simple iteration:

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

However, this approach can be inefficient for larger arrays. PHP offers a more optimized solution using the array_count_values function. This function takes an array as input and returns an array with keys representing the values from the input array and values representing the count of each value.

$counts = array_count_values($array);

The result would be:

array(
    '' => 3,
    'other' => 2
)

To count the number of blank values, simply access the corresponding key:

$blank_count = $counts[''];

This approach is significantly more efficient than the iterative method, especially for large arrays.

The above is the detailed content of How Can I Efficiently Count Occurrences of Specific Values in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn