Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 2 of 10 · Arrays & String Functions
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.

FunctionPurposeReturns
array_map()Transforms every elementNew array, same length
array_filter()Keeps elements matching a conditionNew array, possibly shorter, keys preserved
array_reduce()Combines all elements into a single valueA 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);
// 15

Interview 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?