The below code does not work
as intended.
$fruits = array('apple', 'orange', 'banana', 'cherry');
array_walk($fruits, function($a) {
$a = ucfirst($a);
});
var_dump($fruits);
Why does this work when we pass the reference to an individual entry in the $fruits
array.
array_walk(
$fruits,
function(&$a) {
$a = ucfirst($a);
}
);
Note: I know array_map
and foreach
would work, but why does array_walk()
not work?.
Normally PHP uses Call by Value semantics when evaluating a function. This means that reassignments to parameters will not affect variable bindings in the caller. Because of this the assignment in the "non working" code has no affect outside the callback and thus does not alter the walked array.
However, when a function parameter is specified as &..
(as discussed in Passing By Reference) the semantics switch to Call by Reference. This means that variables in the caller can be altered through reassignment of the parameters. In this case the assignment to the local parameter reassigns the currently iterated array element through Call by Reference semantics and the code "works".
Now, array_walk
"works" this way because it was designed to work with Call by Reference semantics. array_map
, on the other hand, uses the return value of the callback.