This should exactly give the desired output..so modulus was not a bad idea:
function calculateAgeGroup($age)
{
if (!$age) { return null; }
if ($age <= 25) { return '0-25'; }
else if ($age > 50 && $age <= 60) { return '51-60'; }
else if ($age > 60) { return '61-'; }
$age = (($age%5) != 0) ? ($age - ($age%5) + 1) : ($age -= 4);
return $age.'-'.($age+4);
}
Another option, where the values are precomputed:
function calculateAgeGroup($age)
{
$age = ($age <= 25) ? 0 : ($age-1) - (($age-1) % 5);
$age = ($age >= 60) ? 60 : $age;
$ages = array (
0 => '0-25', 25 => '26-30', 30 => '31-35',
35 => '36-40', 40 => '41-45', 45 => '46-50',
50 => '51-60', 55 => '51-60', 60 => '61-',
);
return $ages[$age];
}
I benchmarked the solutions and the first solution with modulus is the fastests from all provided answers since there is not much calculation involved.
It would be even faster if you take the array out of the function and make it global or as (static) class property.
$ages = array (
0 => '0-25', 25 => '26-30', 30 => '31-35',
35 => '36-40', 40 => '41-45', 45 => '46-50',
50 => '51-60', 55 => '51-60', 60 => '61-',
);
function calculateAgeGroup($age)
{
$age = ($age <= 25) ? 0 : ($age-1) - (($age-1) % 5);
$age = ($age >= 60) ? 60 : $age;
global $ages;
return $ages[$age];
}