Which is faster: in_array() or a bunch of expressions in PHP?
Here is an live update of this bench with another case https://3v4l.org/OA2S7
The results for PHP 7.3:
multiple comparisons: 0.057507991790771
in_array: 0.02568507194519
array_flip() outside loop measured + isset(): 0.014678001403809
array_flip() outside loop not measured + isset(): 0.015650033950806
foreach and comparison: 0.062782049179077
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:
$array = array('test1', 'test2', 'test3', 'test4');
$var = 'test';
$iterations = 1000000;
$start = microtime(true);
for($i = 0; $i < $iterations; ++$i) {
if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') {}
}
$end = microtime(true);
print "Time1: ". ($end - $start)."<br />";
$start2 = microtime(true);
for($i = 0; $i < $iterations; ++$i) {
if (!in_array($var, $array) ) {}
}
$end2 = microtime(true);
print "Time2: ".($end2 - $start2)."<br />";
// Time1: 1.12536692619
// Time2: 1.57462596893
slightly trivial note to watch for, if $var
is 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
Time1: 0.20484399795532
Time2: 0.29854393005371
PHP7.1
Time1: 0.064045906066895
Time2: 0.056781053543091
PHP7.4
Time1: 0.048759937286377
Time2: 0.049691915512085
PHP8.0
Time1: 0.045055150985718
Time2: 0.049431085586548
Conclusion: The original test wasnt the best test, and also: In php7+ is has become a matter of preference.
Note that if you're looking to replace a bunch of !==
statements, you should pass the third parameter to in_array
as true
, which enforces type checking on the items in the array.
Ordinary !=
doesn't require this, obviously.
The first will be faster - the second has a lot of overhead: creating the array, calling a function, searching the array...
However, as I said in a question a couple of answers down, premature optimization is the root of all evil. You should write your code to be readable, then if it needs to be optimized profile it, then optimize.
Edit:
My timings with @Owen's code (PHP 5.2.6 / windows):
Time1: 1.33601498604
Time2: 4.9349629879
Moving the array(...) inside the loop, as in the question:
Time1: 1.34736609459
Time2: 6.29464697838