views:

110

answers:

6
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.

+2  A: 

Yes, the corrected version is valid syntax:

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

Question is, what does it mean?

It will compare the result of the expression ($var1 || $var2) which will be a boolean, to the value of $var.

And, as mentioned, php -l file.php will tell you if there are any syntax errors.

Edit:

Consider this:

$var1 = 1;
$var2 = 2;

echo var_dump(($var1 || $var2));

Result is:

bool(true)
George Marian
Corrected. So it is valid?
chustar
@chustar Yes, it is valid. But it is not the same as `if($var == $var1 || $var == $var2)`
banzaimonkey
A: 

You can use the command php -l filename.php from the command line to check for syntax errors.

pshah
A: 

As George Marian says, it's missing a closing parenthesis so would throw a syntax error. It's otherwise valid, though, so I can't see that it's the logical OR construct itself that you're unsure about. It's used in several languages, including javascript.

hollsk
A: 

your corrected example is valid and will be TRUE is $var is TRUE and either $var1 or $var2 is TRUE .. OR . if $var, $var1 and $var2 are all FALSE

Scott Evernden
A: 

it's true and equal to

$var XOR ($var1 OR $var2)
Ehsan
uh i don't think so .. XOR is not the same as EQUALS
Scott Evernden
you're right, I should have said it has same result if variables are boolean :-)
Ehsan
No, it's not the same if the variables are boolean either.
Evert
Would you please explain more?
Ehsan
+8  A: 

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)
Gumbo
+1 there is better explanation.
Sarfraz