PHP Program to Implement Binary Search

PHP Program to Implement Binary Search

Searching is an essential task in programming, and learning efficient search algorithms can make a big difference in the performance of your programs. Binary Search is one of the most important algorithms in computer science. Unlike simple linear search that checks every element one by one, Binary Search works on sorted arrays and uses a divide-and-conquer strategy to find a target value. By repeatedly splitting the search range in half, it can locate elements much faster, especially in large datasets.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Binary Search is widely used in applications that involve large amounts of sorted data, such as searching in databases, looking up words in dictionaries, or finding records in structured arrays. For beginners, understanding Binary Search is not just about finding a number quickly—it also introduces the concept of recursion, iteration, and efficient problem-solving strategies. By learning Binary Search in PHP, you build a foundation that is applicable in many real-world programming scenarios.

Program 1: Iterative Binary Search

This program demonstrates a simple Binary Search using a loop to find a target number in a sorted array.

<?php

$array = [1, 3, 5, 7, 9, 11];
$target = 7;

$low = 0;
$high = count($array) - 1;
$found = false;

while ($low <= $high) {

    $mid = floor(($low + $high) / 2);

    if ($array[$mid] == $target) {

        echo "Element $target found at index $mid.";

        $found = true;
        break;

    } elseif ($array[$mid] < $target) {
        $low = $mid + 1;
    } else {
        $high = $mid - 1;
    }

}

if (!$found) echo "Element $target not found.";

?>

In this iterative approach, the array is repeatedly divided into halves, reducing the number of comparisons significantly. Beginners can understand how narrowing down the search range speeds up the process compared to checking every element. This method is easy to implement and highly efficient for sorted arrays.

Program 2: Recursive Binary Search

Here, we implement Binary Search using recursion, which provides a different perspective on how the algorithm works.

<?php

function binarySearchRecursive($arr, $target, $low, $high) {

    if ($low > $high) return -1;

    $mid = floor(($low + $high) / 2);

    if ($arr[$mid] == $target) return $mid;
    elseif ($arr[$mid] < $target) return binarySearchRecursive($arr, $target, $mid + 1, $high);
    else return binarySearchRecursive($arr, $target, $low, $mid - 1);

}

$array = [2, 4, 6, 8, 10, 12];
$target = 8;
$index = binarySearchRecursive($array, $target, 0, count($array) - 1);

if ($index != -1) echo "Element $target found at index $index using recursion.";
else echo "Element $target not found using recursion.";

?>

The recursive approach helps beginners understand how problems can be broken into smaller subproblems. Each recursive call focuses on a smaller portion of the array, illustrating the divide-and-conquer principle clearly. It also reinforces the use of base cases to end recursion safely.

Program 3: Binary Search Function

Encapsulating Binary Search in a function makes it reusable for different arrays and targets. This program shows a simple iterative version wrapped in a function.

<?php

function binarySearch($arr, $target) {

    $low = 0;
    $high = count($arr) - 1;

    while ($low <= $high) {

        $mid = floor(($low + $high) / 2);

        if ($arr[$mid] == $target) return $mid;
        elseif ($arr[$mid] < $target) $low = $mid + 1;
        else $high = $mid - 1;

    }

    return -1;

}

$array = [1, 2, 3, 4, 5, 6, 7];
$target = 5;
$index = binarySearch($array, $target);

if ($index != -1) echo "Element $target found at index $index using function.";
else echo "Element $target not found using function.";

?>

By using a function, beginners learn modular coding and reusability. This version can be applied to any sorted array with minimal effort, making it practical for real-world programming tasks.

Program 4: Binary Search with Strings

Binary Search can also be applied to strings, provided the array is sorted alphabetically. This program demonstrates that capability.

<?php

$names = ["Albus", "Fred", "George", "Harry", "Hermione"];
$target = "Harry";

$low = 0;
$high = count($names) - 1;
$found = false;

while ($low <= $high) {

    $mid = floor(($low + $high) / 2);

    if ($names[$mid] === $target) {
        echo "Name $target found at index $mid.";
        $found = true;
        break;
    } elseif (strcmp($names[$mid], $target) < 0) {
        $low = $mid + 1;
    } else {
        $high = $mid - 1;
    }

}

if (!$found) echo "Name $target not found.";

?>

This example shows that Binary Search is not limited to numbers. By using strcmp for string comparison, beginners can search names or other text data efficiently in sorted arrays. It highlights the flexibility of the algorithm in real-world applications.

Program 5: Binary Search for Multiple Occurrences

This program demonstrates how to find all occurrences of a target value in a sorted array.

<?php
$array = [1, 2, 2, 2, 3, 4, 5];
$target = 2;
$indices = [];

$low = 0;
$high = count($array) - 1;

while ($low <= $high) {

    $mid = floor(($low + $high) / 2);

    if ($array[$mid] == $target) {

        // Scan left and right for all occurrences
        $i = $mid;

        while ($i >= 0 && $array[$i] == $target) {

            $indices[] = $i;
            $i--;

        }

        $i = $mid + 1;

        while ($i < count($array) && $array[$i] == $target) {

            $indices[] = $i;
            $i++;

        }

        break;

    } elseif ($array[$mid] < $target) {
        $low = $mid + 1;
    } else {
        $high = $mid - 1;
    }

}

if (!empty($indices)) echo "Element $target found at indices: " . implode(", ", $indices) . ".";
else echo "Element $target not found.";

?>

By scanning left and right from the found index, we can locate all instances of the target. Beginners learn how Binary Search can be adapted for more complex needs while maintaining efficiency compared to linear scanning.

Frequently Asked Questions (FAQ)

Binary Search is an efficient algorithm, but beginners often have questions about how it works and when to use it.

Q1: Can Binary Search work on unsorted arrays?
No, Binary Search only works on sorted arrays. Sorting is a prerequisite.

Q2: Is Binary Search faster than Linear Search?
Yes, for large datasets, Binary Search is much faster because it eliminates half of the remaining elements with each comparison.

Q3: Can Binary Search work with strings?
Yes, as long as the array is sorted alphabetically and you use string comparison functions like strcmp.

Q4: What is the time complexity of Binary Search?
The average and worst-case time complexity is O(log n), which makes it very efficient for large datasets.

Q5: Can Binary Search find multiple occurrences?
Yes, by finding one occurrence and scanning left and right, all instances of the target can be located efficiently.

Conclusion

Binary Search is an essential algorithm for efficient searching in sorted arrays. Whether implemented iteratively, recursively, or adapted for strings and multiple occurrences, it provides a fast and reliable way to locate data. Practicing these PHP examples helps beginners understand divide-and-conquer strategies, recursion, and modular coding. Mastering Binary Search lays a strong foundation for tackling larger datasets and preparing for more advanced algorithms in real-world applications.

Scroll to Top