Applying a function to each element of an array
suggest changeTo apply a function to every item in an array, use array_map(). This will return a new array.
$array = array(1,2,3,4,5);
//each array item is iterated over and gets stored in the function parameter.
$newArray = array_map(function($item) {
return $item + 1;
}, $array);
$newArray now is array(2,3,4,5,6);.
Instead of using an anonymous function, you could use a named function. The above could be written like:
function addOne($item) {
return $item + 1;
}
$array = array(1, 2, 3, 4, 5);
$newArray = array_map('addOne', $array);
If the callable is an instance method, pass an array of the object and the method name:
class Example {
public function addOne($item) {
return $item + 1;
}
public function doCalculation() {
$array = array(1, 2, 3, 4, 5);
$newArray = array_map(array($this, 'addOne'), $array);
}
}
Another way to apply a function to every item in an array is array_walk() or array_walk_recursive(). The callback receives the value and then the key of each item. These functions do not return a new array; they return true on success. For example, to print every element in a simple array:
$array = array(1, 2, 3, 4, 5);
array_walk($array, function($value, $key) {
echo $value . ' ';
});
// prints "1 2 3 4 5"
The value parameter of the callback may be passed by reference, allowing you to change the value directly in the original array:
$array = array(1, 2, 3, 4, 5);
array_walk($array, function(&$value, $key) {
$value++;
});
$array now is array(2,3,4,5,6);
For nested arrays, array_walk_recursive() will go deeper into each sub-array:
$array = array(1, array(2, 3, array(4, 5), 6));
array_walk_recursive($array, function($value, $key) {
echo $value . ' ';
});
// prints "1 2 3 4 5 6"
Note: array_walk() and array_walk_recursive() can change values, but not keys. Declaring the key parameter by reference does not rename keys; PHP warns that the key was not passed by reference.