Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short hand to do something like: if($variable == 1 || $variable == "whatever" || $variable == '492') .

Tags:

php

I find my self doing this type of IF statement allot. For example:

if($variable == 1 || $variable == "whatever" || $variable == '492') { ... }  

Except for allot of the time, I am comparing the $variable to maybe 4-5 things, sometimes more. Is there a short hand way to write this? You can see that repeating $variable == would get redundant.

I would love for this to work, but it doesn't:

if($variable == (1 || "whatever" || 492) { ... }
like image 450
Roeland Avatar asked Nov 20 '11 22:11

Roeland


3 Answers

You can use this shorthand, but keep in mind that it is less efficient that explicitly listing them all with or clauses:

if(in_array($variable, array(1, 'whatever', '492'))){ ... }

Also if you want to use === instead of == the equivalent is:

if(in_array($variable, array(1, 'whatever', '492'), TRUE)){ ... }
like image 189
Paul Avatar answered Sep 20 '22 12:09

Paul


if(in_array($variable, array(1, "whatever", 492)))

like image 32
toon81 Avatar answered Sep 17 '22 12:09

toon81


in_array(...). http://php.net/manual/en/function.in-array.php

like image 35
Godwin Avatar answered Sep 19 '22 12:09

Godwin