phpif-statementshorthand-if

nested shorthand if


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

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