bswinnerton
bswinnerton

Reputation: 4721

inline elseif in PHP

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;

Upvotes: 6

Views: 18442

Answers (4)

B.K
B.K

Reputation: 897

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

Upvotes: 0

Sunil Kartikey
Sunil Kartikey

Reputation: 525

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

Upvotes: 3

rid
rid

Reputation: 63542

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 ? ( ... ) : ( ... ) )

Upvotes: 21

CrayonViolent
CrayonViolent

Reputation: 32517

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"

Upvotes: 1

Related Questions