Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP make if shorter

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.

like image 416
James Avatar asked Aug 03 '10 03:08

James


2 Answers

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) {}
like image 97
BoltClock Avatar answered Sep 28 '22 10:09

BoltClock


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.

like image 32
thomasrutter Avatar answered Sep 28 '22 11:09

thomasrutter