Is it faster to do the following:
if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') { ... }
Or:
if (!in_array($var, array('test1', 'test2', 'test3', 'test4') { ... }
Is there a number of values at which point it’s faster to do one or the other?
(In this case, the array used in the second option doesn’t alreay exist.)
i’d strongly suggest just using
in_array(), any speed difference would be negligible, but the readability of testing each variable separately is horrible.just for fun here’s a test i ran:
slightly trivial note to watch for, if
$varis not set, method 1 takes much longer (depending on how many conditions you test)Update for newer PHP versions:
Martijn: I’ved extended the array to five elements, and look for
test3, as sort of an average case.PHP5.6
PHP7.1
PHP7.4
PHP8.0
Conclusion: The original test wasnt the best test, and also: In php7+ is has become a matter of preference.