Binary Search in PHP

Description: Typical binary search done through PHP. It takes an array of values which have a numerical index (not an associative array), a value to search for and the minimum and maximum array index. It returns the index of the value found or -1 if the value was not found.
Tested Platform: PHP 7
Language: PHP
// Takes a non associative array and returns the index of the found value.
// Otherwise it returns -1. MinIndex and MaxIndex are the lowest and highest
// indexes of the array.

function BinarySearch($arNumbers, $searchValue) {
    $min = 0;
    $max = count($arNumbers) - 1;
    
    while ($max >= $min) {
        $midpoint = intval(($max - $min) / 2 + $min);
        
        if ($searchValue > $arNumbers[$midpoint]) { $min = $midpoint + 1; }
        else if ($searchValue < $arNumbers[$midpoint]) { $max = $midpoint - 1; }
        else { return $midpoint; }
    }

    return -1;
}

Posted: March 17, 2023

Return to the snippets listing