0
0
PHPprogramming~20 mins

Array walk function in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Walk 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 code using array_walk?
Consider the following PHP code. What will it output when run?
PHP
<?php
$arr = [1, 2, 3];
array_walk($arr, function(&$value, $key) {
    $value *= 2;
});
print_r($arr);
?>
AArray ( [0] => 1 [1] => 2 [2] => 3 )
BArray ( [0] => 2 [1] => 4 [2] => 6 )
CArray ( [0] => 1 [1] => 4 [2] => 9 )
DArray ( [0] => 0 [1] => 0 [2] => 0 )
Attempts:
2 left
💡 Hint
Remember that array_walk passes values by reference if you want to modify the original array.
Predict Output
intermediate
2:00remaining
What does this PHP code print?
Look at this PHP code using array_walk. What will be printed?
PHP
<?php
$arr = ['a' => 1, 'b' => 2];
array_walk($arr, function($value, $key) {
    echo "$key:$value ";
});
?>
Aa:1 b:2
B1:a 2:b
Ca b
DArray
Attempts:
2 left
💡 Hint
The callback prints key and value pairs separated by a colon.
🔧 Debug
advanced
2:00remaining
Why does this PHP code cause an error?
This PHP code tries to modify array elements using array_walk but causes an error. Why?
PHP
<?php
$arr = [1, 2, 3];
array_walk($arr, function($value) {
    $value *= 2;
});
print_r($arr);
?>
ABecause array_walk requires the callback to return a value.
BBecause array_walk cannot be used with numeric arrays.
CBecause the callback parameter $value is not passed by reference, so original array is unchanged.
DBecause print_r cannot print arrays modified by array_walk.
Attempts:
2 left
💡 Hint
Check how the callback parameters are declared and if they modify the original array.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in this PHP array_walk usage?
Identify which code snippet will cause a syntax error when using array_walk.
Aarray_walk($arr, function(&$v $k) { $v += 1; });
Barray_walk($arr, function($v, $k) { $v += 1; });
Carray_walk($arr, function(&$v, $k) { $v += 1; });
Darray_walk($arr, fn(&$v) => $v += 1);
Attempts:
2 left
💡 Hint
Check the function parameter list syntax carefully.
🚀 Application
expert
3:00remaining
How many items are in the array after this PHP code runs?
Given this PHP code using array_walk, how many items does the array have after execution?
PHP
<?php
$arr = [10, 20, 30];
array_walk($arr, function(&$v, $k) use (&$arr) {
    if ($v > 15) {
        unset($arr[$k]);
    }
});
print_r($arr);
?>
A0
B2
C3
D1
Attempts:
2 left
💡 Hint
Consider what happens when you unset elements during array_walk iteration.