3

I have an array of items on which I would like to apply search function. I am considering sorting the array and simply applying binary search for now as it need not be too complex, however if I run into problems I'll try other methods.

My question is; what is the search algorithm used in the array_search()? If it is indeed binary search I can use that.

1
  • I'd say linear search Commented Jan 31, 2015 at 11:11

3 Answers 3

3

It has to be sequential search, because the array might not be sorted.

If you need to search an array often, use array_flip to convert it to an associative array where the values become the keys. Looking up keys in an array is a hash lookup.

Sign up to request clarification or add additional context in comments.

Comments

2

PHP performs a linear search - here's the source

Comments

2

It isn't a binary search.... it simply loops through the array until it finds the first matching element.... the internal equivalent of

foreach($haystack as $key => $value) { 
    if ($value == $needle) { 
        return $key; 
    }
}

Though for a fast search alternative, a Trie might be better than a binary search

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.