It depends on the PHP version you are using. On PHP 5.3
in_array()
will be slower. But in PHP 5.4 or higher in_array()
will be faster.
Only if you think the condition will grow over time or this condition should be dynamic, use in_array()
.
I did a benchmark. Loop your conditions 10,000 times.
Result for PHP 5.3.10
+----------------------------+---------------------------+
| Script/Task name | Execution time in seconds |
+----------------------------+---------------------------+
| best case in_array() | 1.746 |
| best case logical or | 0.004 |
| worst case in_array() | 1.749 |
| worst case logical or | 0.016 |
| in_array_vs_logical_or.php | 3.542 |
+----------------------------+---------------------------+
Result of PHP 5.4
+----------------------------+---------------------------+
| Script/Task name | Execution time in seconds |
+----------------------------+---------------------------+
| best case in_array() | 0.002 |
| best case logical or | 0.002 |
| worst case in_array() | 0.008 |
| worst case logical or | 0.010 |
| in_array_vs_logical_or.php | 0.024 |
+----------------------------+---------------------------+
Best case: match on first element.
Worst case: match on last element.
This is the code.
$loop=10000;
$cases = array('best case'=> 'a', 'worst case'=> 'z');
foreach($cases as $case => $x){
$a = utime();
for($i=0;$i<$loop; $i++){
$result = ($x == 'a' || $x == 'b' || $x == 'c' || $x == 'd' || $x == 'e' || $x == 'f' || $x == 'g' || $x == 'h' || $x == 'i' || $x == 'j' || $x == 'k' || $x == 'l' || $x == 'm' || $x == 'n' || $x == 'o' || $x == 'p' || $x == 'q' || $x == 'r' || $x == 's' || $x == 't' || $x == 'u' || $x == 'v' || $x == 'w' || $x == 'x' || $x == 'y' || $x == 'z');
}
$b = utime();
$ar = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
for($i=0;$i<$loop; $i++){
$result = in_array($x, $ar);
}
$c = utime();
$Table->addRow(array("$case in_array()", number_format($c-$b, 3)));
$Table->addRow(array("$case logical or", number_format($b-$a, 3)));
}
Here is utime()
is a wrapper of microtime()
that provides microseconds in float and $Table
is a Console_Table
instance.