Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline elseif in PHP

Tags:

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;
like image 267
bswinnerton Avatar asked May 14 '12 21:05

bswinnerton


People also ask

Is there an Elseif in PHP?

In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

What is Elseif?

The ELSEIF operation is the combination of an ELSE operation and an IF operation. It avoids the need for an additional level of nesting. The IF operation code allows a series of operation codes to be processed if a condition is met. Its function is similar to that of the IFxx operation code.

What is the difference between else if and Elseif in PHP?

There is no difference between “elseif” or “else if” just another way to write it. If statements allow multiple elseifs which can then be followed by else. I prefer using 'else if', but that's just by convention and it tends to make the code look a little neater, for me.

How do you end an if statement in PHP?

The endif keyword is used to mark the end of an if conditional which was started with the if(...): syntax. It also applies to any variation of the if conditional, such as if... elseif and if...else .


2 Answers

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 ? ( ... ) : ( ... ) )
like image 120
rid Avatar answered Oct 02 '22 09:10

rid


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

like image 37
Sunil Kartikey Avatar answered Oct 02 '22 10:10

Sunil Kartikey