Skip to content

Instantly share code, notes, and snippets.

@aran112000
Last active May 6, 2020 20:57
Show Gist options
  • Save aran112000/984831c37212f6da163057b2787adb2e to your computer and use it in GitHub Desktop.
Save aran112000/984831c37212f6da163057b2787adb2e to your computer and use it in GitHub Desktop.
Example of a simple function to perform a Binary Search in PHP to search for a String value
<?php
/**
* @param string $value The value you're searching for
* @param array $dataSet Your sorted data set to search
*
* @return int Returns the key matched, or -1 if no match is found
*/
function binarySearchString(string $value, array $dataSet): int
{
$start = 0;
$end = count($dataSet) - 1;
while ($start <= $end) {
$middle = intdiv($end, 2);
if ($value === $dataSet[$middle]) {
return $middle;
}
if (strcmp($value, $dataSet[$middle]) < 0) {
$end = $middle + 1;
continue;
}
$start = $middle - 1;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment