Search code examples
phpevaluationoperator-precedence

Operator "?" and operator AND evaluation


This evaluates to TRUE.

$A = TRUE;
$B = FALSE;

$result = ($A) AND ($B) ? true : false;

Why is the evaluation giving true, and how exactly is the evaluation done step by step?

Thanks


Solution

  • It's not related to the ternary. It's because = has a higher precedence than and. That means you're setting $result = ($A) and then everything after the and is irrelevant.

    ($B) ? true : false does evaluate to false, but because the assignment already happened in the first part of the expression, it's not assigned to anything. It's basically ignored.

    For a more straightforward example, try

    $result = true and false;
    

    $result will be true.