0
0
PHPprogramming~5 mins

Array reduce function in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the array_reduce function do in PHP?
It takes an array and reduces it to a single value by applying a callback function to each element, accumulating the result.
Click to reveal answer
beginner
What are the parameters of array_reduce?
1. The input array<br>2. A callback function that takes the accumulator and current item<br>3. An optional initial value for the accumulator
Click to reveal answer
intermediate
How does the callback function used in array_reduce work?
It receives two arguments: the accumulator (which stores the ongoing result) and the current array element. It returns the updated accumulator.
Click to reveal answer
intermediate
What happens if you don't provide an initial value to array_reduce?
The first element of the array is used as the initial accumulator value, and the reduction starts from the second element.
Click to reveal answer
beginner
Give a simple example of using array_reduce to sum numbers in an array.
Example:<br>
$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item, 0);
echo $sum; // Outputs 10
Click to reveal answer
What does the accumulator represent in array_reduce?
AThe ongoing result of the reduction
BThe current element of the array
CThe original array
DThe callback function
What is the default initial value of the accumulator if not provided in array_reduce?
AAn empty array
Bnull
C0
DThe first element of the array
Which of these is a valid callback signature for array_reduce?
Afunction($array) { return array_sum($array); }
Bfunction($item, $accumulator) { return $item + $accumulator; }
Cfunction($accumulator, $item) { return $accumulator + $item; }
Dfunction() { return 0; }
What will array_reduce return if the input array is empty and no initial value is given?
Anull
B0
Cfalse
DAn error
Which PHP function is best for combining all elements of an array into a single value?
Aarray_filter
Barray_reduce
Carray_map
Darray_merge
Explain how array_reduce works in PHP and describe its parameters.
Think about how you would combine many pieces into one result.
You got /5 concepts.
    Write a simple PHP example using array_reduce to multiply all numbers in an array.
    Start with 1 as initial value for multiplication.
    You got /4 concepts.