Using comparison operators in a PHP 'switch' statement

前端 未结 6 2069
予麋鹿
予麋鹿 2020-12-13 17:41

I have four conditions that I need to go through and I thought it would be best to use the switch statement in PHP. However, I need to check whether an integer

6条回答
  •  情话喂你
    2020-12-13 18:02

    I can also confirm @bytepunk answer here is functional.

    Also, expending the concept with PHP 7

    switch ($interval->days)
    {
        case 0:
            return '1 day';
            // break;
        case (($interval->days >= 1 && $interval->days <= 7) ?? $interval->days):
            return '1 week';
            // break;
        case (($interval->days >= 8 && $interval->days <= 31) ?? $interval->days):
            return '1 month';
            // break;
        case (($interval->days >= 31 && $interval->days <= 93) ?? $interval->days):
            return '2-3 months';
            // break;
        default:
            return '3+ months';
    }
    

    I will admit that this isn't the cleanest of code, so perhaps wrapping each case with a static-like pure function would neat things up a bit, and not forgetting to name each function (or create one generic function with parameters) to match the case. This will make it more readable.

提交回复
热议问题