Search code examples
phpor-operator

How do I write the following OR?


This little piece of code always returns "Equal". I must have something wrong syntax wise but I really can't find what. It's driving me crazy.

<?php

    $var = "1";

    if($var == "2" or "3") {
        echo "Equal";
    } else {
        echo "Different";
    }

  ?>

Solution

  • The string "3" is always true since it is non zero. You need to check against the variable again in the second condition.

    if($var == "2" OR $var == "3") {
        echo "Equal";
    } else {
        echo "Different";
    }
    

    Also, you should use || instead of OR due to unexpected results. Check out the operator precedence. http://php.net/manual/en/language.operators.precedence.php