Reducing with 'array_reduce'
Part of the Logic & Flow section of Coddy's PHP journey — lesson 43 of 68.
The array_reduce() function takes a different approach from array_map() and array_filter(). Instead of returning a new array, it processes all elements in an array to produce a single value. This makes it perfect for operations like calculating totals, finding maximums, or combining all elements into one result.
The function requires three parameters: the array to process, a callback function that defines how to combine elements, and an optional initial value. The callback function receives two parameters: the accumulated result (called the "carry") and the current array element.
<?php
function addNumbers($carry, $item) {
return $carry + $item;
}
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, "addNumbers", 0);
// Result: 15
?>In this example, the function starts with an initial value of 0, then repeatedly calls addNumbers with the running total and each array element. This accumulation process continues until all elements are processed, leaving you with the final reduced value.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive two inputs: a comma-separated list of numbers and an operation type. The first input contains numbers as a string in the format 5,10,15,20,25, and the second input is a single character indicating the operation: S for sum, P for product, or M for maximum.
Read both inputs, convert the comma-separated numbers into an array of integers, create a custom callback function that performs the specified operation, use array_reduce() with your callback function and an appropriate initial value to process all numbers into a single result, and print the final result.
Operation details:
S(Sum): Add all numbers together (initial value: 0)P(Product): Multiply all numbers together (initial value: 1)M(Maximum): Find the largest number (initial value: first number in array or a very small number)
Your callback function should accept two parameters: the accumulated result (carry) and the current array element (item), then return the updated accumulated value based on the operation type.
Input format:
- First line: Comma-separated numbers (example:
5,10,15,20,25) - Second line: Operation type - either
S,P, orM(example:S)
Expected output: A single number representing the result of the reduce operation
Cheat sheet
The array_reduce() function processes all elements in an array to produce a single value, perfect for calculating totals or combining elements.
It requires three parameters: the array to process, a callback function, and an optional initial value. The callback receives the accumulated result (carry) and the current array element.
<?php
function addNumbers($carry, $item) {
return $carry + $item;
}
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, "addNumbers", 0);
// Result: 15
?>Use number_format($total, 2) to format results to 2 decimal places.
Try it yourself
<?php
// Read input
$numbers_input = trim(fgets(STDIN));
$operation = trim(fgets(STDIN));
// Convert comma-separated string to array of integers
$numbers = array_map('intval', explode(',', $numbers_input));
// TODO: Write your code below
// Create a callback function based on the operation type
// Use array_reduce() with your callback function and appropriate initial value
// Output the result
echo $result;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting6Higher-Order Array Functions
Transforming with 'array_map''array_map' with Custom FuncFiltering with 'array_filter''array_filter' with Custom FunReducing with 'array_reduce'Walking with 'array_walk'Recap: Data Processing