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
  • 69,737
  • 10
  • 105
  • 255
morpheous
  • 16,270
  • 32
  • 89
  • 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
  • 310,957
  • 84
  • 592
  • 636
5

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

nc3b
  • 15,562
  • 5
  • 51
  • 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
  • 616,129
  • 168
  • 910
  • 942