I am asking this question considering the performance of script. Knowing that PHP arrays don’t perform very well, I am wandering which way is the best to go down when in this sort of situations.
Suppose if $x equals to a or b or c or d we need action_a() to execute and if not action_b() to execute..
We can either implement this with || operator as follows;
if($x == 'a' || $x == 'b' || $x == 'c' || $x == 'd'){
action_a();
}else{
action_b();
}
Or we can implement this using in_array() as follows;
if(in_array($x,array('a','b','c','d'))){
action_a();
}else{
action_b();
}
What I would like to know is which of these two options would perform well:
-
when the number of possible values for
$xare high? -
when the number of possible values for
$xare low?
Write a benchmark script.
In general though, which variant to pick should hardly ever depend on performance. Especially in super trivial cases where your input data is very very small (say <10).
This most important criteria is always readability.
Only start optimizing code when there is an undeniable performance problem.
Premature optimization is the root of all evil.