Applying a function to each element of an array

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Executing upon an array:
* Applying a function to each element of an array

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
89 Executing upon an array
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR