I have a doubt about what’s the better way to make a fast search in arrays (I’m talking about an specific case).
Supose that I have an array L = [A, B, C] (when I start). While the program is running, may be L will grow (but by the end), one possible case when I’ll do the search is that L = [A, B, C, D, E].
The fact is that when I’m searching, the values that I want find could be only D and E. Now I’m using find_array(elem, array), but this function can’t be “tweaked” to search starting at the end and decreasing the index, and I’m “afraid” that for all the searches the function in_array will examine all the elements with lower indexes before will find the value that I’m searching.
¿There is another search function wich fits better to my problem? ¿How works internally the in_array function?
Thanks in advance
Advertisement
Answer
I assume that in_array
is a linear search from 0 to n-1.
The fastest search will be to store the values as the keys and use array_key_exists
.
$a['foo'] = true; $a['bar'] = true; if (array_key_exists('foo', $a)) ...
But if that’s not an option, you can make your own for indexed arrays quite easily:
function in_array_i($needle, array $a, $i = 0); { $c = count($a); for (;$i < $c; ++$i) if ($a[$i] == $needle) return true; return false; }
It will start at $i
, which you can keep track of yourself in order to skip the first elements.
Or alternatively…
function in_array_i($needle, array $a, $i = 0); { return in_array($needle, $i ? array_slice($a, $i) : $a); }
You can benchmark to see which is faster.