PHP has some great functions (like array_walk) that allow you to process each element in an array. They're generally set up so you specify the array you want processed as the first parameter and a callback function to apply to each element as the second. These functions return booleans indicating success, not a copy of the modified array as you might expect. If you want the array to be modified, you have to pass the array in by reference like array_walk(&$my_array, 'my_callback');
However, in PHP 5.3 and above, if you pass by reference to function call you get a E_DEPRECATED error.
Does anyone know (if there exists) a correct way to use these functions to modify arrays without triggering the errors and without explicitly suppressing them? Are there newer alternatives to these old array processing functions.
The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.
The array_walk() function is an inbuilt function in PHP. The array_walk() function walks through the entire array regardless of pointer position and applies a callback function or user-defined function to every element of the array. The array element's keys and values are parameters in the callback function.
Values are passed by reference implicitly in PHP >= 5.3 as determined by the function definition.
Function definition for array_walk()
:
bool array_walk ( array &$array , callable $funcname [, mixed $userdata = NULL ] )
Note &$array
. As such, you do not need to explicitly pass the array by reference in the function call in PHP >= 5.3.
array_walk($my_array, 'my_callback');
However, you will need to ensure that the callback accepts it's value by reference accordingly (as demonstrated by nickb).
Also take a look at PHP 5.4 Call-time pass-by-reference - Easy fix available?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With