Group array keys into number ranges, possible?
arrays, php
Solution
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) // I use 150 as the "max" age
);
Then, we have your `array_count_values()` output:
$array_count_values = array( 25 => 1, 26 => 3, 10 => 2, 24 => 1); // From OP
Now, we create an array of all ages, where the keys are the age, and the values are the number of people with that age. It needs to be sorted by its keys for the next step.
$all_ages = $array_count_values + array_fill( 0, 150, 0);
ksort( $all_ages);
Finally, I loop over all the age ranges, slice off the age range from the `$all_ages` array, and sum their values to produce an array of the age ranges, with its values corresponding to how many people fell into that 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);` yields the following output:
Array
(
[0-18] => 2
[19-26] => 5
[27-32] => 0
[33-150] => 0
)
Edit: Since you still have access to your original array, you can just calculate how many "unknowns" you had at the very end:
$result['unknown'] = count( array_filter( $original_array, function( $el) {
return empty( $el);
}));
Problem
I have the following array: ``` ( [25] => 1 [26] => 3 [10] => 2 [24] => 1 ) ``` It was created using the `array_count_values()` function in PHP. Actual original array was something like this, before array_count_values... ``` Array ( [0] => 26 [1] => [2] => 18 [3] => 28 [4] => 22 [5] => 21 [6] => 26 [7] => [8] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [16] => [17] => [18] => [19] => [20] => ) ``` These are ages, so how can I group these into age groups? Lets say I want the following age groups: `<= 18` `19-26` `27-32` `> 32` It is supposed to look: ``` ( [<= 18] => 1 [19-26] => 4 [27-32] => 2 [ > 32] => 1 ) ``` Is there a ready function for this? My solution: 1 tedious way would be to create variables of age groups. Than foreach and increase variable ++ for specific age group if key matches range `($min <= $value) && ($value <= $max)`...