Search code examples
phpprogramming-languagessyntaxconditional-statements

Is this valid PHP syntax?


if ($var == ($var1 || $var2))
{
    ...
}

I am considering using this, but am ont sure if it is valid, and there doesn't seem to be somewhere to check.
It seems logically consistent to me but am not sure, and I don't have something to test it on close by.
If it is valid, what other mainstream languages support this sort of construct.

EDIT: The comparison is valid, but not in the way I was thinking.
What I was trying to do was actually the in_array() function, which I just discovered.


Solution

  • Your code is syntactical valid but semantical probably not what you wanted.

    Because $var1 || $var2 is a boolean expression and always yields true or false. And then $var is compared to the result of that boolean expression. So $var is always compared to either true or false and not to $var1 or $var2 (that’s what you’re have probably expected). So it’s not a shorthand to ($var == $var1) || ($var == $var2).

    Now as you already noted yourself, in_array is a solution to this problem if you don’t want to write expressions like ($var == $var1) || ($var == $var2), especially when you have an arbitrary number of values you want to compare to:

    in_array($var, array($var1, $var2))
    

    Which is equivalent to:

    ($var == $var1) || ($var == $var2)
    

    If you need a strict comparison (using === rather than ==), set the third parameter to true:

    in_array($var, array($var1, $var2), true)
    

    Which is now equivalent to:

    ($var === $var1) || ($var === $var2)