Search code examples
phpternary

Understanding the ternary operator


I have the following example:

$a=false;
$b=true;
$c=false;
if($a ? $b : $c){
   echo 'false';
} else {
   echo 'true';
}

I can't seem to understand this statement,and i need someone to explain me how it works...


Solution

  • $a=false;
    $b=true;
    $c=false;
    if($a ? $b : $c){
       echo 'false';
    } else {
       echo 'true';
    }
    

    expands to:

    $a=false;
    $b=true;
    $c=false;
    if ($a) {
      $temp = $b; // TRUE
    } else {
      $temp = $c; //FALSE
    }
    if($temp){
       echo 'false';
    } else {
       echo 'true';
    }
    

    because $a is false, $temp is assigned $c value (which is false), second if checks if $temp is true (which is not), so else statement is executed echo 'true'