8

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?

alk
  • 68,300
  • 10
  • 92
  • 234
morpheous
  • 15,210
  • 32
  • 86
  • 120
  • Not sure if in_array does. I came across this, thought you might find it handy. http://au.php.net/manual/en/function.array-search.php#93352 – Russell Dias May 13 '10 at 10:49

3 Answers3

11

in_array() is O(n). Also see List of Big-O for PHP functions

Community
  • 1
  • 1
ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
5

Since it doesn't require the array to be sorted, I don't see how it could do a binary search.

nc3b
  • 14,524
  • 5
  • 49
  • 63
4

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.

cletus
  • 599,013
  • 161
  • 897
  • 938