Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, is there a short way to compare a variable to multiple values?

Tags:

Basically what I'm wondering if there is a way to shorten something like this:

if ($variable == "one" || $variable == "two" || $variable == "three") 

in such a way that the variable can be tested against or compared with multiple values without repeating the variable and operator every time.

For example, something along the lines of this might help:

if ($variable == "one" or "two" or "three") 

or anything that results in less typing.

like image 431
vertigoelectric Avatar asked May 02 '13 19:05

vertigoelectric


People also ask

What is === in PHP?

=== Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

What is the best way to compare two integer variables in PHP?

The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two inputs to compare and returns true value if both of the values are same (It compares only value of variable, not data types) and return a false value if both of the values are not same.

How do you check if a variable is not equal to multiple values?

To check if a variable is not equal to multiple values:Use the logical and (&&) operator to chain multiple conditions. In each condition, use the strict inequality operator (! ==) to check that the variable is not equal to the value. If all conditions pass, the variable is not equal to any of the values.

How PHP compares data of different types?

How PHP compares values. PHP has a feature called “type juggling”, or “type coercion”. This means that during the comparison of variables of different types, PHP will first convert them to a common, comparable type.


2 Answers

in_array() is what I use

if (in_array($variable, array('one','two','three'))) { 
like image 132
John Conde Avatar answered Oct 13 '22 00:10

John Conde


Without the need of constructing an array:

if (strstr('onetwothree', $variable)) //or case-insensitive => stristr 

Of course, technically, this will return true if variable is twothr, so adding "delimiters" might be handy:

if (stristr('one/two/three', $variable))//or comma's or somehting else 
like image 28
Elias Van Ootegem Avatar answered Oct 13 '22 00:10

Elias Van Ootegem