PHP Applying a function to each element of an array


Example

To 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 named function is a class method the call of the function has to include a reference to a class object the method belongs to:

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() and array_walk_recursive(). The callback passed into these functions take both the key/index and value of each array item. These functions will not return a new array, instead a boolean for 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 let you change the value of array items, but not the keys. Passing the keys by reference into the callback is valid but has no effect.