Searching
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Searching an array means checking items one by one until you find the one you want or run out of items. It is the simplest search, it works on any list, sorted or not, and it is fine for small lists but gets slower as lists grow.
Practical use cases
- Web app: Is this email already registered?. A sign-up form checks the typed email against a short list of invited guests with in_array(). With 30 invitations the check is instant and nobody notices. If the list grows to 300,000 customers, the same line scans all of them on every request, and the form starts to lag.
- Web app: Ctrl+F style find on a page. A help-centre page has a Find box that highlights matching article titles. The JavaScript loops through the titles and tests each one with includes(). For a few hundred articles it feels instant, and no extra data structure is needed.
- System: Scanning log files. Looking for the word ERROR in an unsorted log means reading line after line. No shortcut exists when the data has no order, so tools like grep read everything once, as fast as the disk allows. A simple scan is the honest answer when order is missing.
The story: The Chappal Rack at the Temple
Outside the old temple, hundreds of chappals lay on a long rack. Mira's grandmother had come out, and Mira had to bring her pink pair. There was no number on any slot and nobody had sorted the pairs. It was just a long line.
Mira started at the first slot. Blue? No. Red? No. Black? No. Pink! She stopped right there and did not bother checking the rest of the rack. Her brother Kabir looked at her proudly. "You searched, but you also knew when to stop."
Next day, Kabir hunted for a gold pair that, as it turned out, was not on the rack at all. He had to look at every slot before he could say "not here". That is the price of an unsorted rack.
Looking at items one by one, from the start, until you find the one you want or run out, is called linear search. It works on any array, sorted or not. (If the rack were sorted, a smarter trick called binary search could skip most of it.)
How to spot this problem, and where you need it
You must find out whether an item exists in a list, or where it sits, and need to decide if a simple scan is good enough or will become a slowdown later.
Signs you need it
- The code uses in_array(), array_search(), indexOf(), includes() or a foreach with an if inside, to find one thing.
- The list is small or unsorted, and you only search it once or a few times.
- The same list is searched thousands of times in a loop, and the page time grows with the list size.
Where to use it in a project
- Quick checks against short lists, such as allowed file types, a handful of admin emails or a few feature names.
- Filters and find boxes over a few hundred items already in memory in a React or jQuery front end.
The solution
Walk through the list from the first position. At each item, compare it with the target. As soon as it matches, stop and return the position. If you reach the end, report that it is not there. This is correct for any list. If you will search the same big list often, build a keyed array or sort it once and use a faster method.
Payoff: Before: a full scan of 300,000 emails on every sign-up request. After: a keyed lookup answers in one step, while small lists can keep the simple scan.
Explain it like I am 8
You lost your red crayon in a box of mixed crayons. You pick them out one at a time. The moment you hold the red one, you shout "found it!". If you have emptied the whole box, you shout "it is not here".
How it works, step by step
- Decide what you are looking for (the target).
- Start at index 0 and look at the item there.
- If it matches the target, stop and return its index.
- Otherwise move to the next index and repeat.
- If you pass the last item without a match, return
-1(ornull) to say "not found".
The code in four languages
PHP
<?php
// Linear search: returns the index of the first match, or -1
function linearSearch(array $rack, string $target): int {
for ($i = 0; $i < count($rack); $i++) {
if ($rack[$i] === $target) {
return $i; // found: stop early
}
}
return -1; // looked everywhere, not here
}
$rack = ['Blue', 'Red', 'Black', 'Pink', 'Green'];
echo linearSearch($rack, 'Pink') . PHP_EOL; // 3
echo linearSearch($rack, 'Gold') . PHP_EOL; // -1JavaScript
// Linear search: returns the index of the first match, or -1
function linearSearch(rack, target) {
for (let i = 0; i < rack.length; i++) {
if (rack[i] === target) {
return i; // found: stop early
}
}
return -1; // looked everywhere, not here
}
const rack = ['Blue', 'Red', 'Black', 'Pink', 'Green'];
console.log(linearSearch(rack, 'Pink')); // 3
console.log(linearSearch(rack, 'Gold')); // -1Java
public class Main {
// Linear search: returns the index of the first match, or -1
static int linearSearch(String[] rack, String target) {
for (int i = 0; i < rack.length; i++) {
if (rack[i].equals(target)) {
return i; // found: stop early
}
}
return -1; // looked everywhere, not here
}
public static void main(String[] args) {
String[] rack = {"Blue", "Red", "Black", "Pink", "Green"};
System.out.println(linearSearch(rack, "Pink")); // 3
System.out.println(linearSearch(rack, "Gold")); // -1
}
}Go
package main
import "fmt"
// linearSearch returns the index of the first match, or -1.
func linearSearch(rack []string, target string) int {
for i := 0; i < len(rack); i++ {
if rack[i] == target {
return i // found: stop early
}
}
return -1 // looked everywhere, not here
}
func main() {
rack := []string{"Blue", "Red", "Black", "Pink", "Green"}
fmt.Println(linearSearch(rack, "Pink")) // 3
fmt.Println(linearSearch(rack, "Gold")) // -1
}Time: O(n) · Extra space: O(1). Best case is the first slot (one look); worst case is every slot, which is n looks.
Watch out for
- Returning
0for "not found". Index 0 is a real position, so use-1ornull. - In PHP, writing
if (array_search(...)). A match at index 0 is falsy! Compare with!== false. - Forgetting to stop after the match, which wastes work or returns the last match instead of the first.
Quick check
- What is the worst case for linear search on 1,000 items?
- 1 look
- 10 looks
- 1,000 looks
- Does linear search need the array to be sorted?
- Yes, always
- No, it works on any order
- Only for numbers
- What should the function return when the target is missing?
- -1 (or null)
- 0
- The last index