array_walk
Calls a function for every element of an array.
Syntax
array_walk(array|object &$array, callable $callback, mixed $arg = null): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array|object | The array. |
| $callback | callable | A function that receives the value and the key. |
| $arg | mixed | Optional. An extra argument for the function. |
Return value
trueAlways `true`.
Examples
The value and the key in the function:
<?php
$prices = ['tea' => 250, 'coffee' => 400];
array_walk($prices, function ($price, $name) {
echo $name, ': ', $price, "\n";
});Output:
tea: 250
coffee: 400Changing elements by reference:
<?php
$prices = ['tea' => 250, 'coffee' => 400];
array_walk($prices, function (&$price) {
$price *= 2;
});
echo json_encode($prices);Output:
{"tea":500,"coffee":800}Notes
Unlike array_map(), the function builds no new array and passes the key to the handler. A plain foreach loop does the same and reads more easily.
See also
- array_map — Applies a function to every element of an array.
- array_reduce — Reduces an array to a single value.
Related recipes
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.