In PHP, is there a short way to compare a variable to multiple values?
11,836
Solution 1
in_array()
is what I use
if (in_array($variable, array('one','two','three'))) {
Solution 2
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
Related videos on Youtube
Comments
-
vertigoelectric almost 2 years
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.
-
brbcoding about 11 yearsalways too fast for me John Conde :P
-
vertigoelectric about 11 yearsI did realize this after I posted my question. Guess I jumped the gun. This is a rather brilliant solution and particularly helpful when comparing to several things at once. Thank you. I'll accept it once the site lets me. It says I have to wait.
-
vertigoelectric about 11 years@brbcoding, I still appreciate your efforts.
-
vertigoelectric about 11 yearsI think you have a typo and meant to say "twothr" instead of "thothr", but obviously I know what you meant. At any rate, this is another nice tactic, and in fact, is even shorter. I noticed you used
strstr
the first time andstristr
the second time. What is the difference? -
Elias Van Ootegem about 11 years
strstr
looks for an exact string match (CaseSensitive)stristr
with thei
performs a case-insensiteve comparison. that's the only difference. And yes, that tothr rubbish was a typo :P -
vertigoelectric about 11 yearsAh, okay. That's what I thought the difference was. Also 'thwothr' is still a typo XD
-
Elias Van Ootegem about 11 years@vertigoelectric: aw nips... I just can't seem to get it together today ;)
-
LSerni about 8 yearsUnfortunately that's not enough: this will still approve a value such as "ree" or "wo". You would need to use
"/{$variable}/"
instead of$variable
. While probably slower, thein_array
solution starts to appear cleaner. -
jimasun over 7 years@LSerni: in this case one would need a string like '/one/two/three/', so the first and last fit as well.
-
Code4R7 about 6 yearsshorter:
if (in_array($variable, ['one','two','three'])) {
-
Imnotapotato about 6 yearshow would you handle this with an AND
&&
situation?