Inline elseif in PHP

Is there a way to have a built-in if statement in PHP that also includes elseif?

I would suggest that the logic would look something like this:

$unparsedCalculation = ($calculation > 0) ? "<span style=\"color: #9FE076;\">".$calculation : ($calculation < 0) ? "<span style=\"color: #FF736A;\">".$calculation : $calculation;
+3
source share
4 answers

elseif- it’s nothing but, else iftherefore, practically no elseif, it’s just convenience. The same convenience is not provided for the ternary operator, since the ternary operator is designed for very short logic.

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

coincides with

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

Therefore, the triple equivalent

$a ? ( ... ) : ( $b ? ( ... ) : ( ... ) )
+16
source

you can use nested ternary operator

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

for a better readability coding standard can be found here

+1
source

, , , . "elseif",

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

Although you really shouldn't code it this way ... it is confusing in terms of readability. No one is going to look at it and be "sweet, ninja!". they will say "pah, wtf"

+1
source

Try it,

(($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));
0
source

All Articles