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!