Consider the following PHP code using array_reduce. What will it output?
<?php $numbers = [1, 2, 3, 4]; $result = array_reduce($numbers, function($carry, $item) { return $carry + $item; }, 0); echo $result; ?>
Think about how array_reduce accumulates values starting from the initial value.
The function sums all numbers starting from 0, so 1+2+3+4 = 10.
Look at this PHP code that uses array_reduce to concatenate strings. What is the output?
<?php $words = ['Hello', ' ', 'World', '!']; $result = array_reduce($words, function($carry, $item) { return $carry . $item; }, ''); echo $result; ?>
Remember that the dot operator . joins strings in PHP.
The function joins all array elements into one string, preserving spaces.
Examine this PHP code snippet. Why does it cause an error?
<?php $values = [2, 4, 6]; $result = array_reduce($values, function($carry, $item) { return $carry * $item; }); echo $result; ?>
Think about what happens if you don't provide the initial value for carry.
Without an initial value, carry is null on the first call, so multiplying null by a number causes unexpected behavior.
Choose the correct PHP syntax for using array_reduce with an initial value of 100.
Remember the third argument is the initial value and must be passed inside the parentheses.
Option A correctly passes the initial value as the third argument inside the function call.
Given this PHP code, how many items does the resulting array contain?
<?php $items = [1, 2, 3, 4]; $result = array_reduce($items, function($carry, $item) { if ($item % 2 === 0) { $carry[] = $item * 10; } return $carry; }, []); print_r($result); ?>
Count how many even numbers are in the original array.
The code collects only even numbers multiplied by 10. The even numbers are 2 and 4, so the result has 2 items.