views:

160

answers:

2

What is a true way to write like:

if ($variable == '(value1/value2/value3)' ) { }

It should work similar to:

if ($variable == 'value1' || $variable == 'value2' || $variable == 'value3') { }

Just want to make this code shorter (now I use switch).

Thanks.

+15  A: 

Try in_array():

if (in_array($variable, array('value1', 'value2', 'value3'))) {}

If you do happen to have a group of values separated by, in your example, a /, just explode() it and you'll have an array to plug into in_array():

if (in_array($variable, explode('/', 'value1/value2/value3'))) {}

It might seem like you could just use strpos() instead since it's a long string of values, but that's not how one would work with a delimited string of multiple values (use explode() instead, as above):

if (strpos('value1/value2/value3', $variable) !== false) {}
BoltClock
use `strpos` and get values like "value1/val" or "ue1"
valya
@valya: exactly, which is why `strpos()` isn't the right way to do it even though it might seem to make sense at first :)
BoltClock
But wouldn't it be simple to use a regex? Like: `if(preg_match('/%$6^$%^-`jil9(*` ? Sometimes you guys just don't think straight, if you ask me ;)
karim79
@karim79: ha, that made me chuckle :)
BoltClock
+2  A: 

Also shorter:

if (preg_match('#^(?:value1|value2|value3)$#', $variable) {

Not that it's necessarily the best way to do it. The long way, using just if and || statements, is going to be simple to read even though it's lengthy, and will be the most efficient to run.

thomasrutter