0
0
PHPprogramming~20 mins

Array reduce function in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Reduce Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP array_reduce example?

Consider the following PHP code using array_reduce. What will it output?

PHP
<?php
$numbers = [1, 2, 3, 4];
$result = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $result;
?>
A24
B10
C1234
DError: Undefined variable
Attempts:
2 left
💡 Hint

Think about how array_reduce accumulates values starting from the initial value.

Predict Output
intermediate
2:00remaining
What does this PHP code output when using array_reduce with strings?

Look at this PHP code that uses array_reduce to concatenate strings. What is the output?

PHP
<?php
$words = ['Hello', ' ', 'World', '!'];
$result = array_reduce($words, function($carry, $item) {
    return $carry . $item;
}, '');
echo $result;
?>
AError: Cannot concatenate
BHelloWorld!
CHello World!
DArray
Attempts:
2 left
💡 Hint

Remember that the dot operator . joins strings in PHP.

🔧 Debug
advanced
2:00remaining
Why does this PHP array_reduce code cause an error?

Examine this PHP code snippet. Why does it cause an error?

PHP
<?php
$values = [2, 4, 6];
$result = array_reduce($values, function($carry, $item) {
    return $carry * $item;
});
echo $result;
?>
ABecause the initial value for carry is missing, causing carry to be null on first call
BBecause multiplication operator is invalid in PHP
CBecause array_reduce requires a third argument to specify the array
DBecause echo cannot output numbers
Attempts:
2 left
💡 Hint

Think about what happens if you don't provide the initial value for carry.

📝 Syntax
advanced
2:00remaining
Which option shows the correct syntax for array_reduce with an initial value?

Choose the correct PHP syntax for using array_reduce with an initial value of 100.

A$result = array_reduce($arr, fn($carry, $item) => $carry + $item, 100);
B$result = array_reduce($arr, fn($carry, $item) => $carry + $item); 100;
C$result = array_reduce($arr, fn($carry, $item) => $carry + $item,);
D$result = array_reduce($arr, fn($carry, $item) => $carry + $item 100);
Attempts:
2 left
💡 Hint

Remember the third argument is the initial value and must be passed inside the parentheses.

🚀 Application
expert
3:00remaining
How many items are in the resulting array after this array_reduce operation?

Given this PHP code, how many items does the resulting array contain?

PHP
<?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);
?>
A1
B4
C0
D2
Attempts:
2 left
💡 Hint

Count how many even numbers are in the original array.