This should definitely give the desired result. The module was not a good 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 when the values ββare pre-computed:
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 compared the solutions, and the first solution with the module is the fastest of all the answers provided, since there are not many calculations.
This will be even faster if you select an array from a function and make it global or as a (static) class.
$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]; }
source share