Basic Linear Search

The basic idea of linear search is to iterate through the array and compare each element with the target value until a match is found or the end of the array is reached.

PHP




<?php
  
function linearSearch($arr, $target) {
    $length = count($arr);
  
    for ($i = 0; $i < $length; $i++) {
        if ($arr[$i] == $target) {
              
            // Return index of target element
            return $i;
        }
    }
  
    // Return -1 if target element
    // is not found
    return -1;
}
  
// Driver code
$arr = [10, 20, 30, 40, 50];
$targetValue = 30;
  
$result = linearSearch($arr, $targetValue);
  
if ($result != -1) {
    echo "Element found at index $result";
} else {
    echo "Element not found in the array";
}
  
?>


Output

Element found at index 2

Implementation of Linear Search in PHP

Linear search, also known as sequential search, is a basic method for finding a specific element in an array. In this article, we will explore the implementation of linear search in PHP.

Similar Reads

Basic Linear Search

The basic idea of linear search is to iterate through the array and compare each element with the target value until a match is found or the end of the array is reached....

Linear Search with Enhanced Features

...