skip to Main Content

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 !

2

Answers


  1. $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

    Login or Signup to reply.
  2. $test = (false OR false OR true);
    echo $test; // Outputs: 1 (true)
    
    if ($test) {
       echo "IT'S TRUE"; // Outputs: IT'S TRUE
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search