PHP Elseif Ternary Operators PHP Elseif Ternary Operators php php

PHP Elseif Ternary Operators


$top = ($i == 0) ? '<div class="active item">' : (($i % 5 == 0) ? '<div class="item">' : '');

you need to add parenthesis' around the entire else block


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;}


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.