- array_slice: documentation ( source)
- ceil: documentation ( source)
- range: documentation ( source)
<?php
function BinSearch($needle, $haystack){
(int) $m = ceil(count($haystack) / 2);
$midpoint = $haystack[$m];
$lower_half = array_slice($haystack, 0, $m);
$upper_half = array_slice($haystack, -$m, count($haystack));
if ($needle == $midpoint){ return $haystack[$needle]; }
else if ($needle < $midpoint) {
return BinSearch($needle, $lower_half);
}
else if ($needle > $midpoint) {
return BinSearch($needle, $upper_half);
}
}
$x = range(0,9999);
BinSearch(8273,$x);