Question

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)
 }
}
Was it helpful?

Solution

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) : ''))

OTHER TIPS

Try this!

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top