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

Key Array Functions (array_map, array_filter, array_reduce…)

php PHP 5.0+ Beginner
debt(d4/e2/b2/t5)
d4 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'default linter catches the common case' (d3), +1. phpcs, phpstan, and rector (listed in detection_hints.tools) can catch some misuses like in_array in loops or manual loops replaceable by array_map/filter. However, subtler issues like key-preservation surprises or array_search loose comparison aren't reliably caught by default lint rules — they often require more targeted static analysis rules or code review. Scoring d4 as slightly harder than default linting but not requiring a fully specialist tool.

e2 Effort Remediation debt — work required to fix once spotted

Closest to 'one-line patch or single-call swap' (e1), +1. The quick_fix describes straightforward replacements: swap a foreach for array_map, add array_values() to re-index, replace in_array loop with array_flip+isset. Most fixes are one-to-few-line changes within a single function. Slightly above e1 because some cases (e.g., replacing nested loops with array_column or refactoring a usort callback) require understanding the data flow, but still very localized.

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

Closest to 'minimal commitment' (b1), +1. Array functions are utility-level choices that apply broadly (web, cli, queue-worker across all PHP 5+), but each usage is localized and independent. Choosing array_map over a foreach doesn't impose structural weight on the rest of the codebase. The reach is wide but the commitment per instance is minimal — no architectural coupling or persistent tax.

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

Closest to 'notable trap' (t5). The misconception field describes a documented gotcha that most PHP devs eventually learn: array_map preserves keys on single arrays, array_filter always preserves keys (requiring array_values to re-index), and array_search returns 0 for the first element which is loosely equal to false. These are genuine traps — the 'obvious' assumption about key behavior or return values is wrong — but they're well-documented and commonly known. The usort callback true/false vs negative/zero/positive is another classic gotcha. Collectively these represent notable but not catastrophic traps.

About DEBT scoring →

Also Known As

PHP array functions array_map array_filter array manipulation

TL;DR

PHP's functional array processing functions enable expressive, pipeline-style transformations without explicit loops.

Explanation

PHP provides rich array manipulation: array_map() transforms each element, array_filter() selects elements matching a predicate, array_reduce() aggregates to a single value, usort()/uasort()/uksort() sort with custom comparators, array_column() extracts a column from a multi-dimensional array, and array_combine() pairs keys and values from two arrays. Understanding null handling (array_map with null callback), reference passing pitfalls in foreach, and the difference between array_splice() and array_slice() prevents subtle bugs.

Common Misconception

array_map and array_filter always preserve keys. array_map on a single array preserves keys; array_filter always preserves keys (use array_values() to re-index). Knowing the key behaviour of each function prevents subtle indexing bugs.

Why It Matters

PHP's built-in array functions are implemented in C and outperform equivalent manual loops — using them correctly also makes code more declarative and less error-prone.

Common Mistakes

  • Using a foreach loop to build a new array when array_map() expresses the same transformation more clearly.
  • Using array_search() and assuming false means not found — it returns 0 for the first element, which is loosely equal to false.
  • Not using array_column() for extracting a column from a multi-dimensional array — a common manual loop anti-pattern.
  • Passing the wrong argument order to usort() callback — return negative/zero/positive, not true/false.

Code Examples

✗ Vulnerable
// Manual loop instead of built-in function:
$names = [];
foreach ($users as $user) {
    $names[] = $user['name']; // Use array_column($users, 'name')
}

// Unsafe search:
$pos = array_search($val, $arr);
if ($pos == false) { /* misses index 0 — use !== false */ }
✓ Fixed
// array_map — transform
$prices  = array_map(fn(Product $p) => $p->price * 1.2, $products);

// array_filter — keep truthy or matching
$active  = array_filter($users, fn(User $u) => $u->isActive());
// re-index after filter
$active  = array_values($active);

// array_column — extract column, optionally index by another
$names   = array_column($users, 'name');           // ['Alice','Bob']
$byId    = array_column($users, 'name', 'id');     // [1=>'Alice',2=>'Bob']

// usort — custom sort with spaceship operator
usort($orders, fn($a, $b) => $a->total <=> $b->total);

// array_combine, array_diff, array_intersect
$map     = array_combine($keys, $values);
$missing = array_diff($required, $provided);

Added 15 Mar 2026
Edited 22 Mar 2026
Views 31
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 2 pings F 2 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 2 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 1 ping W 1 ping T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Perplexity 8 Amazonbot 7 Ahrefs 5 Google 2 SEMrush 2
crawler 23 crawler_json 1
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Prefer array_map/array_filter/array_reduce over loops for clarity; use array_column for extracting key columns from 2D arrays; use array_flip for O(1) lookups
📦 Applies To
PHP 5.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
in_array in loop O(n²) — use array_flip + isset O(n); manual loop building result array that array_map/filter would express
Auto-detectable: ✓ Yes phpcs phpstan rector
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Low Context: Function

✓ schema.org compliant