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?✗ Incorrect
The accumulator holds the result as it is built up by processing each element.
What is the default initial value of the accumulator if not provided in
array_reduce?✗ Incorrect
If no initial value is given, the first element of the array is used as the initial accumulator.
Which of these is a valid callback signature for
array_reduce?✗ Incorrect
The callback must accept accumulator first, then current item, and return the updated accumulator.
What will
array_reduce return if the input array is empty and no initial value is given?✗ Incorrect
If the array is empty and no initial value is provided, array_reduce returns null.
Which PHP function is best for combining all elements of an array into a single value?
✗ Incorrect
array_reduce is designed to reduce an array to a single value using a callback.
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.