3

I have a little trouble with a shorthanded if statement I can't figure out

($product == "vindo") ? $this->getNextVindoInList($id) : $this->getNextGandrupInList($id),

This works fine but I want to have another check in that statement. Like this:

if($product == "vindo") {
  if($number != 14) {
    $this->getNextVindoInList($id)
  }
} else {
 if($number != 22) {
    $this->getNextGandrupInList($id)
 }
}
2
  • 4
    Be careful, too much use will result in harder to read code!!! There is also minimal performance gain from it, it's neither faster or slower. Commented Sep 20, 2012 at 12:42
  • 3
    Please, don't it. Short code is not better code. Commented Sep 20, 2012 at 12:48

4 Answers 4

14

For educational purposes, I will leave this answer intact. But it should be known that this is NOT RECOMMENDED. Nesting ternaries is a bad idea. It provides no performance benefit over explicit if-else statements and makes the code much more difficult to read.

That said, see below for how it can, but should not be done.


Two ways:

($product == "vindo" && $number != 14 ? $this->getNextVindoInList($id) : ($number != 22 ? $this->getNextGandrupInList($id) : '')

// Equivalent of:
if ($product == "vindo" && $number != 14)
    $this->getNextVindoInList($id);
else if ($number != 22)
    $this->getNextGandrupInList($id);

// OR

// Equivalent of your example:
($product == "vindo" ? ($number != 14 ? $this->getNextVindoInList($id) : '') : ($number != 22 ? $this->getNextGandrupInList($id) : ''))
Sign up to request clarification or add additional context in comments.

1 Comment

This is old. But someone just upvoted it, which made me come look at it, and want to slap my former self for even presenting this as a good idea. Please avoid nested ternaries. They are unnecessarily difficult to read.
3

Try this!

($product == "vindo") ? ($number != 14 ? $this->getNextVindoInList($id) : null ) : (($number != 22) ? $this->getNextGandrupInList($id) : null)

Comments

2

I will not present a solution with a nested ternary operator. Why? The code with the explicit if/else structure communicates intent. It shows what exactly is happening.

Why sacrifice readability for a few lines? That's quite a bad trade.

Comments

1

Your if statements can be simplefied by using this code:

if($product == "vindo" && $number != 14) {
  $this->getNextVindoInList($id)
} else if($number != 22) {
  $this->getNextGandrupInList($id)
}

The sorthand if isnt handy now because the else has an if statement too.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.