← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Searching Algorithms

algorithms PHP 5.0+ Intermediate

Also Known As

binary search linear search hash lookup search algorithm

TL;DR

Linear search is O(n) and works on any array. Binary search is O(log n) but requires a sorted array. Hash lookup is O(1) and the right choice for most in-memory searches.

Explanation

Linear search: scan each element — O(n), works on unsorted data, unavoidable for some problems. Binary search: halve the search space each step — O(log n), requires sorted data. Finding the midpoint: mid = left + (right - left) / 2 (avoids integer overflow). Binary search applications: finding a value in a sorted array, searching a monotonic function, lower/upper bounds. Hash lookup (PHP array, SplHashMap): O(1) average — best for repeated lookups. For database queries, indexes implement B-tree search (O(log n)).

Diagram

flowchart LR
    subgraph Linear Search O of n
        ARR1[3 7 1 9 4 6 2] -->|scan each| FOUND1[Found 9<br/>at index 3]
    end
    subgraph Binary Search O of log n - sorted only
        ARR2[1 2 3 4 6 7 9<br/>mid=4] -->|target > mid| RIGHT[6 7 9<br/>mid=7] -->|target > mid| FOUND2[Found 9]
    end
    subgraph Hash Lookup O of 1
        KEY[key: 9] --> HASH[hash function<br/>bucket 3] --> VAL[value directly]
    end
    style FOUND1 fill:#d29922,color:#fff
    style FOUND2 fill:#238636,color:#fff
    style VAL fill:#238636,color:#fff

Common Misconception

Binary search is always better than linear search — binary search requires sorted data and has overhead that makes it slower than linear search for small arrays (< ~20 elements).

Why It Matters

Replacing in_array() (linear) with array_flip() + isset() (hash lookup) is O(n) vs O(1) — a common PHP optimisation that turns quadratic loops into linear ones.

Common Mistakes

  • Binary search on unsorted data — produces wrong results silently.
  • Not using array_flip() for repeated membership tests — in_array is O(n) per call; flip once for O(1).
  • Integer overflow in binary search midpoint: (left + right) / 2 — use left + (right - left) / 2.
  • Off-by-one errors in binary search boundaries — test with arrays of size 0, 1, 2, and even/odd.

Code Examples

✗ Vulnerable
// Linear search in loop — O(n²):
$allowed = ['admin', 'editor', 'viewer']; // Could be 1000 roles
foreach ($users as $user) {
    if (in_array($user->role, $allowed)) { // O(n) per user
        grantAccess($user);
    }
}
✓ Fixed
// Hash lookup — O(1) per user, O(n) total:
$allowed = array_flip(['admin', 'editor', 'viewer']); // Flip once
foreach ($users as $user) {
    if (isset($allowed[$user->role])) { // O(1)
        grantAccess($user);
    }
}

// Binary search for sorted data:
function binarySearch(array $arr, int $target): int {
    $left = 0; $right = count($arr) - 1;
    while ($left <= $right) {
        $mid = $left + intdiv($right - $left, 2); // Avoids overflow
        if ($arr[$mid] === $target) return $mid;
        $arr[$mid] < $target ? ($left = $mid + 1) : ($right = $mid - 1);
    }
    return -1;
}

Added 15 Mar 2026
Edited 22 Mar 2026
Views 18
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 7 Perplexity 5 Google 2 Ahrefs 2
crawler 15 crawler_json 1
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Low
⚡ Quick Fix
For sorted arrays use binary search (O(log n)); for unsorted use hash lookup after array_flip (O(1)); avoid linear in_array() on large datasets in hot paths
📦 Applies To
PHP 5.0+ web cli
🔗 Prerequisites
🔍 Detection Hints
in_array() on large array in hot path; linear search on sorted data that could use binary search
Auto-detectable: ✓ Yes phpstan blackfire
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Function Tests: Update

✓ schema.org compliant