phpbackendshorthand-if

Not sure what the value of a is


where:

$b = true;
$c = 0;
$a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));

I'm not sure how to work out a.

So I understand that this is a shorthand operator, and usually it's a case of:

$value ? true : false

meaning

if $a = true { true } else { false };

so:

if $a{
    if $a{
        true;}
    else{
        0;};
else{
 if $0{
    $a;}
else{
    true;}
};

does this make the value of $a true?


Solution

  • The value of $a would be true

    $b = true;
    $c = 0;
    $a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
    

    The shorthand can be interpreted like this:

    if($a) {
      if($a) {
         $a = $b;
      } else {
         $a = $c;
      }
    } else {
      if($c) {
         $a = $a;
      } else {
         $a = $b;
      }
    }
    

    Because $a is false for not existing in the first place, it immediately jumps to the else statement in that. So the only part that matters to you is:

      if($c) {
         $a = $a;
      } else {
         $a = $b;
      }
    

    0 is the same as false, so $c will come back as false, therefore $a is equal to $b, which is true.

    Edit:

    There is some discussion on the notice that is thrown, but this fails to account for the fact that notices are not truly errors and because of this there is no interruption to the code. The result is not Notice: Undefined variable: a, the "result" (think these people mean output) would be blank if it weren't for us determining the value of $a at the end with var_dump. The question was as to what the value of $a becomes, not what appears on your screen.

    Something displaying on your screen in re to a variable not being set has nothing to do with the value of what $a is.

    If you execute the following code, the notice is not the only thing realized:

    $b = true;
    $c = 0;
    $a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
    
    var_dump($a);
    

    So the output is:

    E_NOTICE : type 8 -- Undefined variable: a -- at line 5
    bool(true)
    

    The fact that a notice was thrown does not prevent $a from becoming true.

    Also notices are easily suppressed...

    error_reporting(0);
    $b = true;
    $c = 0;
    $a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
    
    var_dump($a);
    

    would result in $a still becoming true, and without seeing the notice.

    bool(true)