Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanup function which puts age in age group bucket - possible?

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.

like image 376
Max Avatar asked Dec 16 '22 08:12

Max


1 Answers

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;
    }
}
like image 149
Alexander Kononenko Avatar answered May 12 '23 04:05

Alexander Kononenko