Complete the code to calculate the sum of all numbers in the array using array_reduce.
<?php $numbers = [1, 2, 3, 4]; $sum = array_reduce($numbers, [1]); echo $sum; ?>
The array_reduce function takes an array and a callback function. The callback combines elements. To sum, the callback adds $carry and $item.
Complete the code to calculate the product of all numbers in the array using array_reduce.
<?php $numbers = [1, 2, 3, 4]; $product = array_reduce($numbers, [1], 1); echo $product; ?>
To get the product of all numbers, the callback multiplies $carry by $item. The initial value is 1 to avoid zeroing the product.
Fix the error in the callback function to correctly concatenate all strings in the array.
<?php $words = ['Hello', ' ', 'World', '!']; $result = array_reduce($words, [1], ''); echo $result; ?>
To join strings, the callback should concatenate $carry and $item using the dot operator ..
Fill both blanks to create a dictionary with words as keys and their lengths as values using array_reduce.
<?php $words = ['apple', 'banana', 'cherry']; $lengths = array_reduce($words, function($carry, $word) { $carry[[1]] = [2]; return $carry; }, []); print_r($lengths); ?>
$carry as key or value incorrectly.count() instead of strlen().The key should be the word itself ($word), and the value should be its length using strlen($word).
Fill all three blanks to filter and sum only numbers greater than 10 using array_reduce.
<?php $numbers = [5, 12, 7, 20, 3]; $sum = array_reduce($numbers, function($carry, $num) { if ($num [1] 10) { $carry [2]= $num; } return $carry; }, [3]); echo $sum; ?>
The condition checks if the number is greater than 10 (>). If true, add it to $carry using +=. The initial value is 0.