array_map / filter / reduce as FP Patterns
TL;DR
PHP's array_map(), array_filter(), and array_reduce() enable functional-style data transformation pipelines — cleaner than imperative loops for many common patterns.
Explanation
Functional array operations: array_map(fn, array) — transforms each element, returns new array. array_filter(array, fn) — removes elements where fn returns false, preserves keys. array_reduce(array, fn, initial) — folds array to single value. Combining: array_values(array_filter(array_map(fn, $data))). PHP 8.1 arrow functions (fn($x) => $x*2) make these concise. Caveats: array_filter() preserves keys — use array_values() to re-index. array_map() with multiple arrays fills shorter ones with null. For large datasets, generators are more memory-efficient than array_map.
Common Misconception
✗ array_filter() re-indexes the array — it preserves original keys. Use array_values(array_filter($arr)) to get a 0-indexed result.
Why It Matters
FP-style array operations express intent more clearly than imperative loops and are easier to compose, test, and reason about.
Common Mistakes
- Forgetting array_filter preserves keys — causes issues with JSON encoding expecting arrays.
- Using array_map when a generator would use less memory for large datasets.
- Nested array_map/filter — consider a single loop for readability beyond 2 levels.
Code Examples
✗ Vulnerable
$result = [];
foreach ($users as $user) {
if ($user->isActive()) {
$result[] = $user->getName();
}
}
✓ Fixed
$result = array_map(
fn(User $u) => $u->getName(),
array_filter($users, fn(User $u) => $u->isActive())
);
// Sum with reduce:
$total = array_reduce($orders, fn($carry, $o) => $carry + $o->amount, 0);
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
25
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
Perplexity 7
Amazonbot 7
Unknown AI 3
Google 3
ChatGPT 1
Ahrefs 1
Also referenced
How they use it
crawler 19
crawler_json 2
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Low
⚡ Quick Fix
Replace imperative loops with array_map/filter/reduce for simple transformations. Add array_values() after array_filter() when sequential keys are needed.
📦 Applies To
PHP 5.3+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
array_map\(|array_filter\(|array_reduce\(
Auto-detectable:
✗ No
rector
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: Low
Context: Function