6

Is there a way to have an inline if statement in PHP which also includes a elseif?

I would assume the logic would go something like this:

$unparsedCalculation = ($calculation > 0) ? "<span style=\"color: #9FE076;\">".$calculation : ($calculation < 0) ? "<span style=\"color: #FF736A;\">".$calculation : $calculation;
bswinnerton
  • 4,533
  • 8
  • 41
  • 56

4 Answers4

22

elseif is nothing more than else if, so, practically, there is no elseif, it's just a convenience. The same convenience is not provided for the ternary operator, because the ternary operator is meant to be used for very short logic.

if ($a) { ... } elseif ($b) { ... } else { ... }

is identical to

if ($a) { ... } else { if ($b) { ... } else { ... } }

Therefore, the ternary equivalent is

$a ? ( ... ) : ( $b ? ( ... ) : ( ... ) )
rid
  • 61,078
  • 31
  • 152
  • 193
  • While you are correct that nested ternary statements should be enclosed in parentheses, it has nothing to do with if...else if. Ternary in PHP is left-associative (it is evaluated from left to right). http://php.net/manual/en/language.operators.php – Mr Griever May 14 '12 at 22:38
3

you can use nested Ternary Operator

      (IF ? THEN : ELSE) 
      (IF ? THEN : ELSE(IF ? THEN : ELSE(IF ? THEN : ELSE))

for better readability coding standard can be found here

Community
  • 1
  • 1
Sunil Kartikey
  • 525
  • 2
  • 11
1

You need to wrap some of that in parenthesis for order of operation issues, but sure, you could do that. While there is no "elseif" for ternary operators, it's effectively the same thing

if (condition) ? (true) : (false> if (condition) ? (true) : (false));

Though you really shouldn't code like this...it's confusing from a readability perspective. Nobody is going to look at that and be "sweet, ninja!" they will say "ugh, wtf"

CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
0

Try this,

(($condition_1) ? "output_1" : (($condition_2) ?  "output_2" : "output_3"));

In your case it will be:

$unparsedCalculation = (($calculation > 0) ? "<span style=\"color: #9FE076;\">".$calculation : (($calculation < 0) ?  "<span style=\"color: #FF736A;\">".$calculation : $calculation));
B.K
  • 847
  • 10
  • 6