An interesting problem. Here is my solution. First, define an array of age ranges:
$age_ranges = array( array( 0, 18), array( 19, 26), array( 27, 32), array( 33, 150)
Then we get your output from array_count_values() :
$array_count_values = array( 25 => 1, 26 => 3, 10 => 2, 24 => 1);
Now we create an array of all ages, where keys are age and values โโare the number of people with this age. You need to sort it by its keys for the next step.
$all_ages = $array_count_values + array_fill( 0, 150, 0); ksort( $all_ages);
Finally, I iterate over all age ranges, separate the age range from the $all_ages and summarize their values โโto create an array of age ranges, and its values โโcorrespond to the number of people in this age range.
$result = array(); foreach( $age_ranges as $range) { list( $start, $end) = $range; $result["$start-$end"] = array_sum( array_slice( $all_ages, $start, $end - $start + 1)); }
A print_r( $result); outputs the following result :
Array ( [0-18] => 2 [19-26] => 5 [27-32] => 0 [33-150] => 0 )
Edit: Since you still have access to the original array, you can simply calculate how many โunknownsโ you had at the very end:
$result['unknown'] = count( array_filter( $original_array, function( $el) { return empty( $el); }));