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
Release: 2024-12-01 05:52:11
Original
337 people have browsed it

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');
Copy after login

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;
}
Copy after login

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);
Copy after login

The result would be:

array(
    '' => 3,
    'other' => 2
)
Copy after login

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

$blank_count = $counts[''];
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template