Interview question
What is the difference between array_map, array_filter, and array_reduce? array_map, array_filter और array_reduce में क्या अंतर है?
Answer
All three take a callback and an array, but they do fundamentally different things.
| Function | Purpose | Returns |
|---|---|---|
| array_map() | Transforms every element | New array, same length |
| array_filter() | Keeps elements matching a condition | New array, possibly shorter, keys preserved |
| array_reduce() | Combines all elements into a single value | A single value (not an array) |
$nums = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $nums);
// [2, 4, 6, 8, 10]
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
// [1 => 2, 3 => 4]
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
// 15Interview tip: Point out that array_filter() preserves original keys - a common gotcha when the result is later re-indexed with array_values() before use in a foreach expecting sequential keys.
तीनों callback और array लेते हैं, पर fundamentally अलग काम करते हैं।
| Function | उद्देश्य | रिटर्न |
|---|---|---|
| array_map() | हर element transform करता है | नया array, same length |
| array_filter() | condition matching elements रखता है | नया array, छोटा हो सकता है, keys preserved |
| array_reduce() | सभी elements को एक वैल्यू में जोड़ता है | एक वैल्यू (array नहीं) |
$nums = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $nums);
// [2, 4, 6, 8, 10]
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
// [1 => 2, 3 => 4]
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
// 15इंटरव्यू टिप: बताएं array_filter() original keys preserve करता है - एक आम गोचा जब result को बाद में array_values() से re-index करना पड़ता है sequential keys के लिए।
Was this answer clear?