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

849

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*is`0`

. - The value of each element with a key greater than
*N*is`{-code-1}`

.

This is the array:

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

## Answer

## Solution:

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.## Answer

## Solution:

`array_search`

is your best bethttp://php.net/manual/en/function.array-search.php