PHP Program to Implement Linear Search

PHP Program to Implement Linear Search

Searching is one of the most basic and important operations in programming. Whether you are looking for a specific number in a list, a name in a contact book, or a value in a database, knowing how to search efficiently can save time and make your programs more useful. Linear Search is the simplest search algorithm. It checks each element of an array one by one until it finds the target value. While it may not be the fastest for very large datasets, its simplicity makes it a great starting point for beginners.

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

Linear Search is particularly useful when dealing with unsorted data or small arrays. It does not require the array to be sorted and works equally well with numbers, strings, or other types of data. By understanding Linear Search, beginners gain a foundation for more advanced searching techniques, such as binary search, and can immediately apply it to real-world scenarios like checking if a product exists in stock or verifying user input.

Program 1: Basic Linear Search Using Loops

This program demonstrates the classic linear search by scanning an array element by element to find a specific value.

<?php

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

for ($i = 0; $i < count($array); $i++) {

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

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

        $found = true;
        break;

    }

}

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

?>

This basic program checks each element in sequence and stops as soon as it finds the target. Beginners can easily follow this approach because it uses simple loops and conditionals. It’s useful for understanding how a straightforward search works before moving to more advanced techniques.

Program 2: Linear Search Using a Function

Here, we encapsulate linear search in a function so it can be reused to search multiple arrays without rewriting the code.

<?php

function linearSearch($arr, $target) {

    for ($i = 0; $i < count($arr); $i++) {
        if ($arr[$i] == $target) return $i;
    }

    return -1;

}

$array = [8, 4, 2, 7, 10];
$target = 7;
$index = linearSearch($array, $target);

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

?>

By wrapping the logic in a function, beginners learn modular programming. The function can be called with different arrays and target values, demonstrating how reusable code simplifies development and testing.

Program 3: Linear Search for Strings

Linear search is not limited to numbers. This program demonstrates searching for a string in an array of names.

<?php

$names = ["Harry", "Hermione", "Ron", "Fred", "George"];
$target = "Ron";
$found = false;

for ($i = 0; $i < count($names); $i++) {

    if ($names[$i] === $target) {
        echo "Name $target found at index $i.";
        $found = true;
        break;
    }

}

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

?>

By using strings, beginners can see that linear search works for different data types. The program emphasizes that searching is about comparing values, whether numbers or text, and helps build real-world skills like searching names in a list or user entries in a form.

Program 4: Linear Search Using Recursion

Linear search can also be implemented recursively, which is a good exercise for learning recursion in PHP.

<?php

function recursiveLinearSearch($arr, $target, $index = 0) {

    if ($index >= count($arr)) return -1;
    if ($arr[$index] == $target) return $index;
    return recursiveLinearSearch($arr, $target, $index + 1);

}

$array = [5, 1, 3, 8, 2];
$target = 8;
$index = recursiveLinearSearch($array, $target);

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

?>

The recursive approach shows beginners another way to implement the same algorithm. While loops are often more efficient, recursion helps understand problem-solving in terms of breaking tasks into smaller pieces, a useful skill for more complex algorithms.

Program 5: Linear Search with Multiple Occurrences

This program demonstrates how to find all occurrences of a target value in an array rather than just the first one.

<?php

$array = [2, 4, 2, 7, 2, 9];
$target = 2;
$indices = [];

for ($i = 0; $i < count($array); $i++) {
    if ($array[$i] == $target) $indices[] = $i;
}

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

?>

This program introduces the idea of handling multiple matches, which is common in real-world applications like searching a list of products or students with the same score. Beginners learn to store results and process multiple occurrences, enhancing practical understanding.

Frequently Asked Questions (FAQ)

Linear Search is simple but often raises beginner questions. Understanding these points helps clarify its use and limitations.

Q1: When should I use Linear Search?
Linear Search is best for small or unsorted arrays where simplicity is more important than efficiency.

Q2: Is Linear Search faster than Binary Search?
For small arrays or unsorted data, yes. For large sorted arrays, Binary Search is faster.

Q3: Can Linear Search work with strings and numbers?
Yes, it works with any data type that can be compared.

Q4: Is Linear Search efficient for large datasets?
Not really. Its time complexity is O(n), which means it can be slow for very large arrays.

Q5: Can Linear Search find multiple occurrences?
Yes, by storing all matching indices instead of stopping at the first match.

Conclusion

Linear Search is the foundation of searching algorithms. Its simplicity makes it ideal for beginners to understand how searching works, whether with numbers or strings. By practicing loops, functions, recursion, and handling multiple occurrences, learners can master linear search and build the skills needed for more advanced algorithms. Practicing these PHP examples will help beginners confidently search data in arrays and prepare for efficient programming in real-world applications.

Scroll to Top