Does in_array() use a binary search algorithm?
-
26-09-2019 - |
Question
I have a largish array of string that I want to use as a look-up.
I am using in_array()
, but I suspect its doing a simple loop through - does anyone know whether the in_array()
algo uses a bsearch algo?
Solution
in_array()
is O(n)
.
Also see List of Big-O for PHP functions
OTHER TIPS
Since it doesn't require the array to be sorted, I don't see how it could do a binary search.
in_array()
uses a linear (O(n)) search rather than a binary (O(log n)) search.
If you want O(log n) or better I would suggest you either put the values you want to search as the keys in an array or you create an index structure that effectively does the same thing.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow