I have this function which categorizes the age of a user in a certain age group:
private function calculateAgeGroup($age)
{
if (!$age) {
return null;
}
if ($age <= 25) {
return '0-25';
}
if ($age <= 30) {
return '26-30';
}
if ($age <= 35) {
return '31-35';
}
if ($age <= 40) {
return '36-40';
}
if ($age <= 45) {
return '41-45';
}
if ($age <= 50) {
return '46-50';
}
if ($age <= 60) {
return '51-60';
}
return '61-';
}
Is there a way to simplify (meaning: less verbose, less if statements) this? My first thought was about using modulo, but I dismissed that very fast as it just doesn't make sense to use modulo here.
Second option would be something like floor($age/10)*10 . "-" . ceil($age/10)*10
but that also doesn't work in all cases.
The last option which came to my mind would be using a series of () ? :
statements which would make for shorter but NOT more readable code. Also not so good.
Anyone has any good idea how to simplify this? Suggestions appreciated.
Try this code:
function calculateAgeGroup($age) {
switch($age) {
case $age <= 25:
return '0-25';
break;
case $age > 50 && $age <= 60:
return '51-60';
break;
case $age > 60:
return '61-';
break;
default:
return (floor(($age-1)/5)*5+1) . "-" . ceil($age/5)*5;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With