← Home ← Codex ← DEBT ← Engine
Browse by Category
+ added · updated 7d
← Back to glossary

Searching Algorithms

Algorithms PHP 5.0+ Intermediate
debt(d5/e3/b3/t5)
d5 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'specialist tool catches' (d5), phpstan and blackfire profiler can flag in_array() in hot paths or O(n) lookups; binary search bugs on unsorted data are silent though, leaning toward d5-d7.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3), quick_fix is replacing in_array() with array_flip()+isset() or swapping to binary search — pattern-level substitution, not architectural.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3), search choice is usually scoped to specific hot paths or components rather than system-wide; applies_to covers web/cli but each use is localised.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5), the misconception that binary search is always better and the silent wrong-result trap on unsorted data are classic documented gotchas most devs learn the hard way.

About DEBT scoring →

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 86
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping T 0 pings F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 2 pings T 0 pings W 0 pings T 1 ping F 0 pings S 3 pings S 0 pings M 0 pings T 0 pings W 1 ping T 2 pings F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W 1 ping T 0 pings F
No pings yet today
Sogou 1
Google 9 Amazonbot 8 PetalBot 8 Ahrefs 6 SEMrush 6 Perplexity 5 ChatGPT 5 Scrapy 5 Claude 4 Bing 2 Twitter/X 2 Applebot 2 Meta AI 1 Baidu 1 Sogou 1
crawler 60 crawler_json 5
🧱 FUNDAMENTALS — new to this? Start with the ground floor.
Traversal algorithms Traversal is the process of visiting every element in a data structure exactly once, following a specific order or strategy to access each node or item.

Traversal is the foundation of nearly every algorithm that processes collections—searching, sorting, pathfinding, and serialization all depend on visiting elements in a controlled order. Mastering traversal patterns unlocks your ability to work with any data structure.

💡 Always check for null/None before accessing children, and always track visited nodes in graphs.

Ask Codex about Traversal →
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