0
0
PHPprogramming~10 mins

Array walk function in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to apply a function to each element of the array using array_walk.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry'];
function printFruit($item) {
    echo $item . "\n";
}
array_walk($fruits, [1]);
?>
Drag options to blanks, or click blank then click option'
AprintFruit
Bprint
Cecho
Darray_map
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'print' or 'echo' directly as the callback causes errors.
Passing 'array_map' instead of a callback function.
2fill in blank
medium

Complete the code to modify each element of the array by appending ' fruit' using array_walk.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry'];
function addFruitSuffix(&$item) {
    $item .= [1];
}
array_walk($fruits, 'addFruitSuffix');
print_r($fruits);
?>
Drag options to blanks, or click blank then click option'
A' fruit'
B"fruit"
C'fruit'
D" fruit"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the space before 'fruit' causes words to join without space.
Using single quotes without space changes output formatting.
3fill in blank
hard

Fix the error in the code to correctly print keys and values using array_walk.

PHP
<?php
$colors = ['red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF'];
function printColor($value, [1]) {
    echo "$key: $value\n";
}
array_walk($colors, 'printColor');
?>
Drag options to blanks, or click blank then click option'
Aindex
Bkey
Citem
Dcolor
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than 'key' causes undefined variable error.
Swapping the order of parameters causes wrong output.
4fill in blank
hard

Fill both blanks to create an array_walk callback that prints the key and value separated by a colon.

PHP
<?php
$items = ['pen' => 1.5, 'notebook' => 2.0, 'eraser' => 0.5];
function printItem([1], [2]) {
    echo "$key: $value\n";
}
array_walk($items, 'printItem');
?>
Drag options to blanks, or click blank then click option'
Avalue
Bitem
Ckey
Dprice
Attempts:
3 left
💡 Hint
Common Mistakes
Reversing the order of parameters.
Using variable names that don't match the echo statement.
5fill in blank
hard

Fill all three blanks to create a callback that appends the key in parentheses to each value in the array.

PHP
<?php
$animals = ['cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo'];
function appendKeyToValue(&[1], [2]) {
    $[1] .= ' (' . [2] . ')';
}
array_walk($animals, 'appendKeyToValue');
print_r($animals);
?>
Drag options to blanks, or click blank then click option'
Asound
Bkey
Cvalue
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable names causing undefined variable errors.
Not passing the first parameter by reference.