Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functions like array_walk (and similar functions) to modify arrays in PHP >= 5.3

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.

like image 528
Ray Avatar asked Jul 23 '12 16:07

Ray


People also ask

What exactly is the the difference between Array_map Array_walk and Array_filter?

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.

What is Array_walk?

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.


1 Answers

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?

like image 136
Jason McCreary Avatar answered Sep 19 '22 12:09

Jason McCreary