Advertisement
Intermediate PHP, Arrays in PHP

How do array_map, array_filter, and array_reduce help you transform and process array data without writing manual loops?

Short answer

array_map applies a given function to every element of an array and returns a new array with the transformed values, array_filter returns a new array containing only the elements that pass a given test function, and array_reduce combines all elements of an array into a single…

Save PHP mock interview
Advertisement
AModel answer
array_map applies a given function to every element of an array and returns a new array with the transformed values, array_filter returns a new array containing only the elements that pass a given test function, and array_reduce combines all elements of an array into a single value by repeatedly applying a function, together letting you express common data transformations concisely and clearly instead of writing verbose manual foreach loops.
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
Real-world example
An order processing system uses array_map to convert a list of product prices into their tax inclusive totals, and array_reduce to calculate the grand total of an entire shopping cart in a single clear expression.
Likely follow-ups
  • What is the performance difference between array_map and a manual foreach loop?
  • Can array_filter preserve the original array keys?
Related topics