phpshorthandshorthand-if

How to read spagetti php shorthand if statement ( ternary operators) and conver it into if and else statement


Someone wrote this 'stunning' short hand encapsulated statement. I am sure its not even suppose to be done like this, but I want to dissect it for someone else (myself as well) to be able to understand it well by break it down into if and else statement. I wonder where exactly is the way it should be broke down the statement with. the ? and : position really confused me and make me can get down to nowhere! (i.e. there is ? after another ? how that could be?

$cust->is_company() ? 'TekCustomer__'.($cust->getID() ? $cust->getID() : 'new'.($next_new_id-1)) : 'Person__'.($cust->people[0]->getID() ? $cust->people[0]->getID() : 'new'.$next_new_id++) 

Solution

  • I would highly recommend against the use of nested ternary operators. As you have found out they are far from readable. Converting to proper if statements here will certainly make it more readable. We can start by formatting it a bit to help break it down:

    $cust->is_company() ? 
        'TekCustomer__'.($cust->getID() ? $cust->getID() : 'new'.($next_new_id-1)) :
         'Person__'.($cust->people[0]->getID() ? $cust->people[0]->getID() : 'new'.$next_new_id++)
    

    Aha! It's actually not quote as horrible as it first looks (especially due to PHP's odd behaviour on nested ternarys*).

    First off it's checking $cust->is_company() and doing one of two things. This gives us:

    if($cust->is_company()){
        'TekCustomer__'.($cust->getID() ? $cust->getID() : 'new'.($next_new_id-1));
    }else{
        'Person__'.($cust->people[0]->getID() ? $cust->people[0]->getID() : 'new'.$next_new_id++)
    }
    

    Note here that generally you would do something with the values. This will depend on how the expression was originally used.

    I'll leave the inner ternarys as an exercise for the reader!

    *PHP resolves nested ternary operators left to right rather than right to left. See http://php.net/manual/en/language.operators.comparison.php