The array reduce function helps you combine all items in an array into a single value. It is like adding or multiplying all numbers together step by step.
Array reduce function in PHP
<?php function array_reduce(array $array, callable $callback, mixed $initial = null): mixed { // $array is the list of items // $callback is a function that takes two inputs: the current result and the next item // $initial is the starting value for the result } ?>
The callback function must accept two parameters: the accumulator (result so far) and the current item.
The initial value is optional. If not given, the first array element is used as the initial value.
<?php $numbers = [1, 2, 3, 4]; $sum = array_reduce($numbers, function($carry, $item) { return $carry + $item; }, 0); echo $sum; // 10 ?>
<?php $words = ['Hello', ' ', 'World']; $sentence = array_reduce($words, function($carry, $item) { return $carry . $item; }, ''); echo $sentence; // Hello World ?>
<?php $empty = []; $result = array_reduce($empty, function($carry, $item) { return $carry + $item; }, 0); echo $result; // 0 ?>
<?php $single = [5]; $product = array_reduce($single, function($carry, $item) { return $carry * $item; }, 1); echo $product; // 5 ?>
This program shows how to use array_reduce to sum numbers, multiply them, find the maximum, and handle an empty array safely.
<?php // Create an array of numbers $numbers = [2, 4, 6, 8]; // Print the original array echo "Original array: "; print_r($numbers); // Use array_reduce to sum all numbers $sum = array_reduce($numbers, function($accumulator, $currentItem) { return $accumulator + $currentItem; }, 0); // Print the sum echo "Sum of numbers: " . $sum . "\n"; // Use array_reduce to find the product of all numbers $product = array_reduce($numbers, function($accumulator, $currentItem) { return $accumulator * $currentItem; }, 1); // Print the product echo "Product of numbers: " . $product . "\n"; // Use array_reduce to find the maximum number $max = array_reduce($numbers, function($accumulator, $currentItem) { return ($currentItem > $accumulator) ? $currentItem : $accumulator; }); // Print the maximum number echo "Maximum number: " . $max . "\n"; // Use array_reduce on an empty array with initial value $emptyArray = []; $sumEmpty = array_reduce($emptyArray, function($accumulator, $currentItem) { return $accumulator + $currentItem; }, 0); // Print result for empty array echo "Sum of empty array: " . $sumEmpty . "\n"; ?>
Time complexity is O(n) because it processes each item once.
Space complexity is O(1) as it uses a fixed amount of extra memory.
Common mistake: forgetting to provide an initial value can cause unexpected results with empty arrays.
Use array_reduce when you want to combine array items into one value. For simple sums, PHP also has array_sum which is faster.
array_reduce combines all items in an array into a single value using a callback function.
It works by carrying a result through each step and updating it with the current item.
Always consider providing an initial value to avoid errors with empty arrays.
Practice
array_reduce do?Solution
Step 1: Understand the purpose of array_reduce
The function takes an array and a callback to combine elements into one value.Step 2: Compare with other array functions
Unlike sorting or filtering, array_reduce accumulates values into one result.Final Answer:
It combines all elements of an array into a single value using a callback function. -> Option BQuick Check:
array_reduce = combine elements [OK]
- Confusing array_reduce with sorting functions
- Thinking it filters elements instead of combining
- Assuming it splits arrays into parts
array_reduce in PHP?Solution
Step 1: Recall the official function signature
The correct order is array, callback, then optional initial value.Step 2: Check each option's parameter order
Only array_reduce(array $array, callable $callback, mixed $initial = null) matches the correct order and types.Final Answer:
array_reduce(array $array, callable $callback, mixed $initial = null) -> Option DQuick Check:
array first, callback second, initial last [OK]
- Swapping callback and array parameters
- Placing initial value before callback
- Misordering parameters causing errors
$numbers = [1, 2, 3, 4];
$result = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo $result;Solution
Step 1: Understand the callback function
The callback adds the current item to the carry (accumulated sum).Step 2: Calculate the sum step-by-step
Starting with 0, add 1, then 2, then 3, then 4: 0+1=1, 1+2=3, 3+3=6, 6+4=10.Final Answer:
10 -> Option AQuick Check:
Sum of 1+2+3+4 = 10 [OK]
- Forgetting initial value causes null carry
- Concatenating instead of adding numbers
- Expecting product instead of sum
array_reduce:
$values = [];
$result = array_reduce($values, function($carry, $item) {
return $carry + $item;
});
echo $result;Solution
Step 1: Check initial value usage
No initial value is given, so $carry starts as null.Step 2: Understand effect on empty array
With empty array and no initial, array_reduce returns null without calling the callback.Final Answer:
Missing initial value causes $carry to be null. -> Option CQuick Check:
Initial value needed for empty arrays [OK]
- Assuming callback parameters are reversed
- Thinking array_reduce fails on empty arrays without initial
- Ignoring PHP syntax for echo
['apple', 'banana', 'cherry'], how can you use array_reduce to create a single string with all fruits separated by commas (e.g., 'apple,banana,cherry')?Solution
Step 1: Understand the goal
We want to join strings with commas into one string.Step 2: Design the callback
Callback should add a comma between carry and item, starting with empty string.Step 3: Avoid leading comma
Use a condition to avoid comma before first item or trim later.Final Answer:
Use array_reduce with callback concatenating carry and item with a comma, initial value as empty string. -> Option AQuick Check:
Concatenate strings with commas using array_reduce [OK]
- Adding strings as numbers causing errors
- Not providing initial value causing null carry
- Using multiplication on strings
Ready to prove it?
Pass the test and this pattern moves unknown
