php - Find the first appearance of a number in associative array


Let's say the following is true:

  • I have an associative array containing an unknown number of elements.
  • The keys are integers, starting at{-code-1}, and each is one more than the last.
  • There is an element with key N whose value is{-code-1}.
  • The value of each element with a key less than N is0.
  • The value of each element with a key greater than N is{-code-1}.

This is the array:

enter image description here

The question is : What is the fastest/smartest way to find the position of the first '{-code-1}' in the array?




If you truly don't know the length of the array (a very odd situation), then probably all you can do is grow your search geometrically, i.e. skip 4, skip 8, skip 16, etc. until you find a 1, then cut back with a (geometric) binary search.

People are also looking for solutions to the problem: javascript - How to clear the pre-post values of form fields after submit, and fill the form again with the blank fields


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.