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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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) { ... }
How to&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)){ ... }

Answer:

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

Answer:

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

Answer:

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.

Answer:

Another viable alternative is to use a regex.

if (preg_match('^1|whatever|492$', $variable)) { ... }