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.
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) {}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With