PHP Program for Linear Search with Example and Explanation
foreach loop to check each element in an array and returns the index if the target is found, like foreach ($arr as $index => $value) { if ($value === $target) return $index; }.Examples
How to Think About It
Algorithm
Code
<?php function linearSearch(array $arr, $target) { foreach ($arr as $index => $value) { if ($value === $target) { return $index; } } return -1; } $numbers = [1, 3, 5, 7, 9]; $target = 5; $result = linearSearch($numbers, $target); if ($result !== -1) { echo "Element found at index $result"; } else { echo "Element not found"; }
Dry Run
Let's trace the search for target 5 in the array [1, 3, 5, 7, 9].
Check index 0
Value is 1, target is 5, no match.
Check index 1
Value is 3, target is 5, no match.
Check index 2
Value is 5, target is 5, match found.
| Index | Value | Target | Match? |
|---|---|---|---|
| 0 | 1 | 5 | No |
| 1 | 3 | 5 | No |
| 2 | 5 | 5 | Yes |
Why This Works
Step 1: Loop through array
The foreach loop goes through each element one by one to check for the target.
Step 2: Compare elements
Each element is compared with the target using === to ensure exact match.
Step 3: Return index or -1
If a match is found, the index is returned immediately; otherwise, after checking all elements, -1 is returned.
Alternative Approaches
<?php function linearSearchFor(array $arr, $target) { for ($i = 0; $i < count($arr); $i++) { if ($arr[$i] === $target) { return $i; } } return -1; } $numbers = [1, 3, 5, 7, 9]; $target = 7; $result = linearSearchFor($numbers, $target); echo $result !== -1 ? "Element found at index $result" : "Element not found";
<?php $numbers = [1, 3, 5, 7, 9]; $target = 9; $index = array_search($target, $numbers, true); if ($index !== false) { echo "Element found at index $index"; } else { echo "Element not found"; }
Complexity: O(n) time, O(1) space
Time Complexity
The search checks each element once until it finds the target or reaches the end, so it takes linear time proportional to the array size.
Space Complexity
No extra space is needed besides a few variables, so space complexity is constant.
Which Approach is Fastest?
Using PHP's built-in array_search is usually fastest and simplest, but manual loops give more control and clarity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual foreach loop | O(n) | O(1) | Learning and control |
| For loop with index | O(n) | O(1) | Index control and iteration |
| array_search function | O(n) | O(1) | Quick and simple searches |
=== in PHP to avoid unexpected matches during linear search.