Reputation: 5135
I came across some code today where a string is compared to two values at the same time. I've never seen this before - will this work? Can someone explain it to me?
$foo = 'date';
if ($foo == ('date' || 'datetime')) {
echo "Hello world";
}
Upvotes: 0
Views: 69
Reputation: 116110
That won't work. Write if ($foo == 'date' || $foo == 'datetime')
.
Not only won't ||
work for selecting from a set, but also you use used a single =
, which is for assignment rather than comparison.
In this case, the constant strings are compared using the boolean or operator. To do that, they are both converted to boolean. Since they are non-empty strings, they evaluate to true
. true or true returns true, which is assigned to which is compared to $foo. That comparison will always be true if $foo is 'date' or 'datetime' or about any other non-empty string.$foo
So, whatever the previous value of $foo was, or even if it wasn't assigned at all, the if-expression always evaluates to true, so you always get the echo, and $foo will always be true
afterwards.
Upvotes: 3
Reputation: 219938
This'll not work. ('date' || 'datetime')
always evaluates to true
.
Use this instead:
$foo = 'date';
if ($foo == 'date' || $foo == 'datetime') {
echo "Hello world";
}
Upvotes: 3
Reputation: 174957
No. the ||
or OR
operators only work with Booleans. you'll need this condition:
if ($foo == 'date' || $foo == 'datetime') { ... }
But what if you have 10 possible values? You'll need one for each? yes and no.
Another possibility is to insert all the possible values into an array and check whether your value is possible by comparing it to that array, using in_array()
:
$possible_values = array('date', 'datetime');
if (in_array($foo, $possible_values)) { ... }
Upvotes: 0
Reputation: 253318
You could try the following:
$haystack = array("date","datetime");
$needle = "date";
if (in_array($needle,$haystack)) {
// do something
}
Upvotes: 1