1

I don't understand what's going on here in PHP. I've spent hours on this until I understood that it doen't work normally, or that I dont understand something.

Here the few lines :

$test = false OR false OR true;
echo $test;

Here $test is false, nothing is printed. Also, if I try:

$test = false OR false OR true;
if($test){
    echo "IT'S TRUE";
}

Nothing is printed.

BUT HERE :

if(false OR false OR true){
    echo "IT'S TRUE";
}

"IT'S TRUE" is printed.

So the statement "false OR false OR true" is false when assigned to a variable, but true when is a condition. Does anyone know and can explain to me why ?

EDIT : the answer was that :

$test = false OR false OR true;

is parsed like

($test = false) OR false OR true;

So I need to write :

$test = (false OR false OR true);

And it's work. Thanks all !

Lomchat
  • 19
  • 3
  • 1
    Although it doesn't look like, this question is about the same thing as yours: ['AND' vs '&&' as operator](https://stackoverflow.com/questions/2803321/and-vs-as-operator) It's called "operator precedence" and explains, which operators are "binding" more to their operands. And `=` binds more than `and` or `or`. – cyberbrain Jul 16 '23 at 10:02

1 Answers1

3
$test = false OR false OR true;

Is actually parsed as:

($test = false) OR false OR true;

Hence why the $test evaluates to false in your condition.

See here for more details: https://www.php.net/manual/en/language.operators.logical.php

Gugu72
  • 2,052
  • 13
  • 35