QA
Beginner LevelPHP 8+

How do functional array manipulation methods (array_map, array_filter, array_reduce) work in PHP?

❓ Interview Prompt: Compare array_map(), array_filter(), and array_reduce() functional programming transformations and key preservation rules.

PHP provides higher-order functional utilities for array transformations:

1. 'array_map($callback, $array)':

•
Applies callback to every element, returning a new array of transformed values.
•
Parameter Order: Callback comes FIRST, array comes SECOND.

2. 'array_filter($array, $callback)':

•
Returns a new array containing only elements where callback returns 'true'.
•
Key Preservation: Preserves original array keys! Use 'array_values()' afterwards if you need re-indexed 0-based keys.
•
Parameter Order: Array comes FIRST, callback comes SECOND.

3. 'array_reduce($array, $callback, $initial)':

•
Iteratively reduces an array to a single aggregated value (sum, string concatenation).

Code Implementation Example

php
<?php
$prices = [10, 20, 30, 40];

// 1. array_map: Double every price
$doubled = array_map(fn($p) => $p * 2, $prices); // [20, 40, 60, 80]

// 2. array_filter: Filter prices > 25 (preserves keys 2 and 3!)
$filtered = array_filter($prices, fn($p) => $p > 25);
$reindexed = array_values($filtered); // Re-indexes keys [0 => 30, 1 => 40]

// 3. array_reduce: Sum total prices
$total = array_reduce($prices, fn($carry, $p) => $carry + $p, 0); // 100
💡Functional transformations using array_map, array_filter, and array_reduce.
🎯 Interview Key Takeaway

array_map transforms elements; array_filter filters elements while preserving keys; array_reduce aggregates an array into a single value.

#array_map#array_filter#array_reduce#Functional#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?