PHP Elseif Ternary Operators

后端 未结 3 506
半阙折子戏
半阙折子戏 2020-12-15 05:08

I am trying to convert the following code into a Ternary Operator, but it is not working and I am unsure why. I think my problem is that I do not know how to express the

相关标签:
3条回答
  • 2020-12-15 05:49
    $top = ($i == 0) ? '<div class="active item">' : (($i % 5 == 0) ? '<div class="item">' : '');
    

    you need to add parenthesis' around the entire else block

    0 讨论(0)
  • 2020-12-15 05:49

    Too late probably to share some views, but nevertheless :)

    1. Use if - else if - else for a limited number of evaluations. Personally I prefer to use if - else if - else when number of comparisons are less than 5.
    2. Use switch-case where number of evaluations are more. Personally I prefer switch-case where cases are more than 5.
    3. Use ternary where a single comparison is under consideration (or a single comparison when looping), or when a if-else compare is needed inside the "case" clause of a switch structure.
    4. Using ternary is faster when comparing while looping over a very large data set.

    IMHO Its finally the developer who decides the trade off equation between code readability and performance and that in turn decides what out of, ternary vs. if else-if else vs. switch-case, can be used in any particular situation.

    0 讨论(0)
  • 2020-12-15 06:12

    The Ternary Operator doesn't support a true if... else if... else... operation; however, you can simulate the behavior by using the following technique

    var name = (variable === 1) ? 'foo' : ((variable === 2) ? 'bar' : 'baz');
    

    I personally don't care for this as I don't find it more readable or elegant. I typically prefer the switch statement.

    switch (variable) {
        case 1 : name = 'foo'; break;
        case 2 : name = 'bar'; break;
        default : name = 'bas'; break;
    }
    
    0 讨论(0)
提交回复
热议问题