Reputation:
I was curious, is there a way to compress this condition with logic :
if($var1 == 'foo' || $var2 == 'foo' OR $var3 == 'foo')
to something more compact like:
if(($var1 ||$var2 || $var3) == 'foo')
I think php don't allow it, but I'm curipous to know if there is a "logic trick" to do something more or less like that (even if the condition is finally longer than the original) ?
Upvotes: 0
Views: 46
Reputation: 74220
After testing out a few possibilities, I think that in_array()
is your best option. John's answer is one of those and the original / first answer given; this is just a supplement to.
You could do it this way and setup an array beforehand, if that is what you're looking to do, for any other added variables.
$var1 = "foo"; // yep
$var2 = "foo2"; // nope
$var3 = "foo3"; // nope
$var4 = "foo"; // yep
$vars = array("$var1","$var2","$var3","$var4");
if (in_array("foo", $vars)) //Founds a match !
{
echo "Yep";
}
else
{
echo "Nope";
}
Upvotes: 0
Reputation: 609
You could have:
if (($var1 == $var2) && ($var2 == $var3)) {
// hurrah they're the same
}
Upvotes: 0
Reputation: 219884
in_array()
can shorten this up a bit:
if (in_array('foo', array($var1, $var2, $var3))) {
}
Upvotes: 2