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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…