<?php
function binarySearch(array $arr, int $target): int
{
$low = 0;
$high = count($arr) - 1;
while ($low <= $high) {
// compute middle index
$mid = floor(($low + $high) / 2);
if ($arr[$mid] > $target) {
// search the left side of the array
$high = $mid -1;
} else if ($arr[$mid] < $target) {
// search the right side of the array
$low = $mid + 1;
} else {
// element found at mid
return $mid;
}
}
// If we reach here element x doesnt exist
return -1;
}
// Driver code
$arr = [1, 2, 3, 4, 5];
$target = 3;
$result = binarySearch($arr, $target);
if($result !== -1) {
echo "Target '$target' exists at position $result";
} else {
echo "Target '$target' does not exist";
}
Double search is a search method used to find an element in a sorted array.