Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_walk or array_map?

I'm currently using array_map to apply callbacks to elements of an array. But I want to be able to pass an argument to the callback function like array_walk does. I suppose I could just use array_walk, but I need the return value to be an array like if you use array_map, not TRUE or FALSE.

So is it possible to use array_map and pass an argument to the callback function? Or perhaps make the array_walk return an array instead of boolean?

like image 625
Kemal Fadillah Avatar asked May 10 '11 16:05

Kemal Fadillah


People also ask

What is the difference between array_walk and array_map?

array_map returns a new array, array_walk only returns true . Hence, if you don't want to create an array as a result of traversing one array, you should use array_walk .

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.

What is array_map function in PHP?

The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. Tip: You can assign one array to the function, or as many as you like.


3 Answers

You don't need it to return an array.

Instead of:

$newArray = array_function_you_are_looking_for($oldArray, $funcName);

It's:

$newArray = $oldArray;
array_walk($newArray, $funcName);
like image 120
Lightness Races in Orbit Avatar answered Oct 13 '22 17:10

Lightness Races in Orbit


If you want return value is an array, just use array_map. To add additional parameters to array_map use "use", ex:

array_map(function($v) use ($tmp) { return $v * $tmp; }, $array);

or

array_map(function($v) use ($a, $b) { return $a * $b; }, $array);
like image 33
Hieu Vo Avatar answered Oct 13 '22 18:10

Hieu Vo


Depending on what kind of arguments you need to pass, you could create a wrapped function:

$arr = array(2, 4, 6, 8);
function mapper($val, $constant) {
    return $val * $constant;
}

$constant = 3;
function wrapper($val) {
    return mapper($val, $GLOBALS['constant']);
}

$arr = array_map('wrapper', $arr);

This actually seems too simple to be true. I suspect we'll need more context to really be able to help.

like image 37
sdleihssirhc Avatar answered Oct 13 '22 18:10

sdleihssirhc