Linear Search with PHP

Linear Search with PHP


In the realm of programming, searching for specific elements within a dataset is a common task. One straightforward approach is the linear search algorithm. In this article, we'll explore the concept of linear search and demonstrate its implementation using PHP.

Linear search, also known as sequential search, is a simple searching algorithm that sequentially checks each element in a dataset until the desired element is found or the entire dataset is traversed. It is particularly useful for unsorted or small datasets where efficiency is not a critical factor.

Implementing Linear Search in PHP:

Let's dive into the implementation of the linear search algorithm using PHP. We'll start by defining a function called linearSearch that takes in two parameters: the target value we want to find and an array to search within.

function linearSearch($target, $array) {
    $length = count($array);
    for ($i = 0; $i < $length; $i++) {
        if ($array[$i] === $target) {
            return $i; // Element found, return its index
    return -1; // Element not found

Explanation of the Implementation:

  1. The linearSearch function takes two parameters: $target (the value to search for) and $array (the array to search within).

  2. We determine the length of the array using the count function and store it in the $length variable.

  3. We iterate over each element in the array using a for loop. The loop variable $i represents the index.

  4. Inside the loop, we check if the current element at index $i matches the target value using the === operator.

  5. If a match is found, we return the index $i, indicating the position of the element in the array.

  6. If the loop finishes without finding a match, we return -1 to indicate that the element was not found in the array.

Example Usage: Now, let's see the linear search algorithm in action with an example:

$data = [10, 25, 8, 17, 42, 13];
$target = 42;

$result = linearSearch($target, $data);

if ($result === -1) {
    echo "Element not found in the array.";
} else {
    echo "Element found at index: " . $result;

In this example, we have an array called $data containing some integer values. We want to find the target value 42 using the linearSearch function. If the target is found, we display the index; otherwise, we output a "not found" message.


Linear search provides a basic yet effective method for searching elements within an array. Although it may not be the most efficient algorithm for large or sorted datasets, it serves as a fundamental building block for more complex search algorithms. In this article, we explored the concept of linear search and demonstrated its implementation using PHP. By understanding this algorithm, you'll be equipped to tackle simple search tasks efficiently.