Basic search
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Basic search, or linear search, means looking at items one by one from the start until you find the one you want or run out. It is the simplest way to find something and is perfectly good when the list is short.
Practical use cases
- Web app: Is this coupon valid?. A checkout page has a handful of active coupon codes in an array. Looping through them to see if the typed code matches is plenty fast with 10 items. Using something fancier would only add code without any visible benefit.
- Web app: Checking a short cart. A cart rarely has more than a few dozen lines. To see if a product is already in the cart, the code simply loops through the lines with array_search or find. It is easy to read and the user cannot tell the difference.
- Web app: Finding a setting in a small config list. An admin settings page holds around 30 options. Scanning them in order to find the one called "timezone" is simple and quick. The loop is easy to read and easy to change later, and nobody needs an index for a list that fits on one screen.
- System: Ctrl+F on a page. Browser find-in-page walks through the text from the top looking for your word. For a page of normal length the result appears instantly, so the browser does not need to build any special structure first.
The story: Raju and the Lost Order
Every morning Raju's chai stall in the mohalla gets busy, with school kids, office-goers and aunties all shouting orders at once. He writes each customer's name on a long pad, one under the other, in the order they arrive. Asha, Dev, Zoya, Imran, Leela, Raju's own cousin... the list grows.
One day a lady shouts, "I ordered earlier, did you write down Leela?" Raju has no clever trick. He puts his finger on the first name and reads: "Asha, no. Dev, no. Zoya, no. Imran, no. Leela, yes!" He found it on the fifth line.
That is linear search, also called a sequential search: look at the items one by one, from the start, and stop the moment you find what you want. If the name is not there, you must read every line before you can say so. It is the simplest search in the world, and it works on any list, tidy or messy.
How to spot this problem, and where you need it
You need to know whether something is in a list, or where it is, and the list is small or has no order you can use, so simply looking at each item is the sensible choice.
Signs you need it
- The list is short, say under a few hundred items, and the search happens occasionally, not thousands of times a second.
- The items are in no particular order and you only search once, so sorting first would cost more than just scanning.
- The problem says "find the first element that..." or "return the index, or -1 if not found".
Where to use it in a project
- Small lookups in a cart, dropdown options, permission lists or feature flags.
- One-off scripts, imports and tests where clarity matters more than raw speed.
The solution
Start at the first item and compare it to what you want. If it matches, stop and return its position. If not, move to the next. If you pass the last item without a match, report not found. Use it when the list is small or searched rarely; switch to a map or sorted search when the list grows large or searches become frequent.
Payoff: For 20 items the loop takes a few checks and no setup. Simple code, no bugs, and no visible delay.
Explain it like I am 8
Imagine a row of closed lunch boxes and you are hunting for the one with a laddu. You open the first box, then the second, then the third. When you see the laddu, you shout "Found it!" and stop. That is all linear search is.
How it works, step by step
- Start at the first item (position 0).
- Compare it with what you want. Match? Return its position and stop.
- No match? Move one step to the next item.
- If you run past the last item, the thing is not in the list. Return -1 (or "not found").
The code in four languages
PHP
<?php
// Return the position of $target, or -1 when it is not in the list.
function linearSearch(array $items, string $target): int {
foreach ($items as $i => $item) { // look at every item in order
if ($item === $target) {
return $i; // found: stop immediately
}
}
return -1; // reached the end: not found
}
$names = ['Asha', 'Dev', 'Zoya', 'Imran', 'Leela', 'Raju'];
echo linearSearch($names, 'Leela'), "\n"; // 4
echo linearSearch($names, 'Mira'), "\n"; // -1JavaScript
// Return the position of target, or -1 when it is not in the list.
function linearSearch(items, target) {
for (let i = 0; i < items.length; i++) { // look at every item in order
if (items[i] === target) {
return i; // found: stop immediately
}
}
return -1; // reached the end: not found
}
const names = ['Asha', 'Dev', 'Zoya', 'Imran', 'Leela', 'Raju'];
console.log(linearSearch(names, 'Leela')); // 4
console.log(linearSearch(names, 'Mira')); // -1Java
public class Main {
// Return the position of target, or -1 when it is not in the list.
static int linearSearch(String[] items, String target) {
for (int i = 0; i < items.length; i++) { // look at every item in order
if (items[i].equals(target)) {
return i; // found: stop immediately
}
}
return -1; // reached the end: not found
}
public static void main(String[] args) {
String[] names = {"Asha", "Dev", "Zoya", "Imran", "Leela", "Raju"};
System.out.println(linearSearch(names, "Leela")); // 4
System.out.println(linearSearch(names, "Mira")); // -1
}
}Go
package main
import "fmt"
// linearSearch returns the position of target, or -1 when it is not in the list.
func linearSearch(items []string, target string) int {
for i, item := range items { // look at every item in order
if item == target {
return i // found: stop immediately
}
}
return -1 // reached the end: not found
}
func main() {
names := []string{"Asha", "Dev", "Zoya", "Imran", "Leela", "Raju"}
fmt.Println(linearSearch(names, "Leela")) // 4
fmt.Println(linearSearch(names, "Mira")) // -1
}Time: O(n) · Extra space: O(1). Best case you find it at once; worst case you read all n items. Only a few variables are needed.
Watch out for
- Forgetting the "not found" case and returning 0, which looks like "found at the first position". Use -1.
- Using
==in PHP/JS and getting surprising matches between "5" and 5. Prefer the strict===. - Not stopping after the match and walking the whole list anyway.
Quick check
- Linear search needs the list to be...
- Sorted
- Free of duplicates
- Nothing special, any order works
- In the worst case, how many items does it look at for a list of n items?
- Half of them
- Just one
- All n
- What should the function return when the item is missing?
- 0
- The last position
- -1 (or another "not found" marker)