把年龄放在年龄组桶中的清理功能可能吗?

Max*_*Max 4 php code-cleanup

我有这个功能,它对某个年龄组中用户的年龄进行分类:

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-';
}
Run Code Online (Sandbox Code Playgroud)

有没有办法简化(意思是:更简洁,更少的陈述)这个?我的第一个想法是关于使用modulo,但我很快就认为它很快,因为在这里使用modulo是没有意义的.

第二种选择是类似的,floor($age/10)*10 . "-" . ceil($age/10)*10但在所有情况下都不起作用.

我想到的最后一个选项是使用一系列() ? :语句,这些语句会产生更短但不易读的代码.也不太好.

任何人都有任何好主意如何简化这个?建议表示赞赏.

Ale*_*nko 5

试试这段代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)