Many PHP developers use nested loops for data lookups or joins. But in some cases, a simple hash map (associative array) can make your code several times faster.
Let’s compare them with two short benchmarks (10 000 records each).

1). Joining Users and Orders by Email Naive nested loops:
~480 ms on 10 000×10 000 items
Using a hash map:
~80 ms — about 6× faster
Complexity drops from O(n²) to O(n).
2). When a Simple Loop Is Still Better Task:
count all orders with amount > 1000.
Plain loop:
~1.8 ms
Unnecessary hash:
~2.4 ms — slower, more memory, no gain.
Use hash maps for lookups. When you need to find something fast — like matching a user by email or checking if an ID exists — a hash map wins. It finds items in constant time O(1), even with thousands of records.
Use loops for simple scans. When you just go through everything once — counting, summing, or filtering — a loop is perfect. It’s simple, clear, and uses less memory.
Bottom line: Don’t over-optimize small loops. But if you ever write a nested loop — stop and ask yourself: “Can this be a hash map instead?"


