Search code examples
phpternary

Understanding a Ternary Statement


I'm ready thought some old code and have come across this :

$sal = isset($_REQUEST['c_sal']) ? " " : ($_REQUEST['sal'] ? (Valid($_REQUEST['sal']) ? $_REQUEST['sal'] : false) : null);

I'm trying to work out what it does. I know it's doing some form of validation at one point.. but how do I revert this back to a simple if elseif statement ?

So I can understand exactly what it's doing ?


Solution

  • The following ternary operation

    $sal = isset($_REQUEST['c_sal']) ? " " : ($_REQUEST['sal'] ? (Valid($_REQUEST['sal']) ? $_REQUEST['sal'] : false) : null);
    

    Is the same as the following if statement:

    if(isset($_REQUEST['c_sal'])){
        $sal = " ";
    } else {
        if($_REQUEST['sal']){
            if(Valid($_REQUEST['sal'])){
                 $sal = $__REQUEST['sal'];
            else {
                 $sal = false;
            }
        } else {
            $sal = null;
        }
    }
    

    EDIT: For your info. The ternary without your function:

    $sal = isset($_REQUEST['c_sal']) ? " " : (isset($_REQUEST['sal']) ? $_REQUEST['sal'] : null);