|
Posted by ZeldorBlat on 07/03/07 22:03
On Jul 3, 5:25 pm, "David T. Ashley" <d...@e3ft.com> wrote:
> I have an array of a few hundred integers, ordered in ascending order.
>
> Given an integer input, I'd like to find the index in the array of the
> element $array[$i] such that it is equal to or less than the input but
> $array[$i+1] is larger.
>
> I couldn't find a function to deal with arrays that does anything except
> look for an exact match.
>
> Are there any built-in functions that will search in a "bracketed" way
> rather than look for an exact match?
>
> For example,
>
> $a = array( 10, 50, 250, 1000, 20000, 40000 );
>
> If the input is 20,039 (for example), I'd want the output of the function to
> be 4, because $a[4] is the element just below 20,001.
>
> Any such built-in function?
> --
> David T. Ashley (d...@e3ft.com)http://www.e3ft.com (Consulting Home Page)http://www.dtashley.com (Personal Home Page)http://gpl.e3ft.com (GPL Publications and Projects)
If the array keys are sequential you could use array_reduce like this:
function bracketSearch($arr, $val) {
return array_reduce($arr, create_function('$v,$w','return $w > ' .
$val . ' ? $v : ++$v;'), -1);
}
Alternatively you could just do it the really easy way:
function bracketSearch($arr, $val) {
foreach($arr as $k => $v)
if($v <= $val)
return $k;
}
Navigation:
[Reply to this message]
|