Using comparison operators in a PHP 'switch' statement

前端 未结 6 2065
予麋鹿
予麋鹿 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:07

    What about using ternary operators?

    $priority =
        // "switch" comparison for $count
        $count <= 20 ? 'low' :
        ($count <= 40 ? 'medium' :
        ($count <= 60 ? 'high' :
        // default above 60
        'severe'));
    

    I know the common complaint that ternary operators can be hard to understand, but this is just too easy to do with a simple ?:.

    It operates like the Excel "If" formula

    =IF( logical_test, value_if_true, value_if_false )
    
    $variable = logical_test ? value_if_true : value_if_false
    

    And you can nest the if statements (place a second ?: in the 'value_if_false' section of the first one), which is certainly where it can become confusing to read, but less so when you write it out line by line, as above.

    My code above is basically equivalent to the if() statement written by the OP.

提交回复
热议问题