8

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) { ... }
Roeland
  • 3,698
  • 7
  • 46
  • 62

6 Answers6

10

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)){ ... }
Paul
  • 139,544
  • 27
  • 275
  • 264
  • You probably should have linked the [comparison ===](http://php.net/manual/ro/language.operators.comparison.php) to its manual. Many new programmers don't know what those 3 equal signs mean. – machineaddict Sep 08 '14 at 06:11
4

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

toon81
  • 868
  • 1
  • 5
  • 13
2

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

Godwin
  • 9,739
  • 6
  • 40
  • 58
1

Although this doesn't directly answer the question, I think it's worth adding this method as part of a solution to the above problem:

If you find that something has multiple values, you may find that something like the following is appropriate:

if (true === is_condition_one ( $variable )) {

  // Execute any condition_one logic here

}

function is_condition_one ( $variable = null ) {
  $arrKnownConditions = array (
    // This can be an array from the database
    // An array from a file
    // An array from any other source
    // or an array of hardcoded values
  );

  return in_array ( $variable, $arrKnownConditions );

}

I agree with Godwin and toon81 and PaulPRO, but feel that if you are doing this a lot, you may actually benefit from a refactor as part of your solution. The refactor above may help you organise this project and others better by defining the purpose of the comparison and letting your code be more readable and abstracting away those hardcoded values to a function. This will probably also help you re-use that check in other parts of your code with greater confidence.

MyStream
  • 2,533
  • 1
  • 16
  • 33
0

Answer in 2023

In the new php update, you can also use your suggested method

$variable = "492" ;
if($variable  == 1 || "whatever" || '492'){
    echo "true";
}

Another example

if($testvar =! 0 && ($variable  == 1 || "whatever" || '492')){
    echo "true";
}
0

Another viable alternative is to use a regex.

if (preg_match('^1|whatever|492$', $variable)) { ... }
phatfingers
  • 9,770
  • 3
  • 30
  • 44