PHP Sequential or Linear Search Algorithm

Sequential search, or linear search, is the simplest searching algorithm. Indeed, given it’s brute force approach of just traversing a collection from the first to last element, it’s hard to justify calling it an algorithm at all. However, here’s an example in PHP:

function sequential_search($needle,$haystack) {
for($i = 0; $i < count($haystack); $i++) { if ($needle == $i) return true; } return false; }

Here's an example of how you would use this algorithm to look for the number 3 inside an array:


$haystack = array(1,2,3,4);
$needle = 3;
$success = sequential_search($needle, $haystack);

Leave a Comment

*
To prove you're a person (not a spam script), type the answer to the math equation shown in the picture. Click on the picture to hear an audio file of the equation.
Click to hear an audio file of the anti-spam equation