Recall & Review
beginner
What does the
array_walk() function do in PHP?It applies a user-defined function to every element of an array, allowing you to modify or use each element.
Click to reveal answer
beginner
How do you define the callback function used in
array_walk()?The callback function takes at least one parameter: the value of the current element, passed by reference if you want to modify it. It can also take a second optional parameter for the key.
Click to reveal answer
intermediate
What is the difference between
array_walk() and array_map()?array_walk() applies a function to each element and can modify the original array by reference. array_map() returns a new array with the results and does not modify the original array.Click to reveal answer
beginner
Can
array_walk() modify the original array elements?Yes, if the callback function uses the value parameter by reference, it can change the original array elements.
Click to reveal answer
beginner
Write a simple example of
array_walk() that appends '!' to each string in an array.Example:<br><pre>function addExclamation(&$item, $key) {
$item .= '!';
}
$array = ['Hi', 'Hello', 'Hey'];
array_walk($array, 'addExclamation');
// Result: ['Hi!', 'Hello!', 'Hey!']</pre>Click to reveal answer
What parameters does the callback function for
array_walk() receive?✗ Incorrect
The callback function receives the value and key of each element to allow processing or modification.
Does
array_walk() return a new array?✗ Incorrect
array_walk() returns true on success or false on failure; it does not return a new array.How can you modify the original array elements inside the callback?
✗ Incorrect
Passing the value parameter by reference (&$item) allows modifying the original array elements.
Which function is better to create a new array with modified values without changing the original array?
✗ Incorrect
array_map() returns a new array with modified values, leaving the original unchanged.What happens if the callback function in
array_walk() does not accept the key parameter?✗ Incorrect
The callback can accept just the value parameter; the key is optional and ignored if not declared.
Explain how
array_walk() works and how it can modify an array.Think about how you can change each item in a list by visiting them one by one.
You got /4 concepts.
Compare
array_walk() and array_map() in terms of modifying arrays.Consider whether you want to change the original list or create a new one.
You got /4 concepts.