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.
=== 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.
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.
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 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.
in_array()
is what I use
if (in_array($variable, array('one','two','three'))) {
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With