PHP 8 reference · Array Functions
PHP array_walk() Function
Run a callback on every element of an array, with the value and key. Take the value by reference to change it in place.
PHP 8 Since 4.0
Syntax
array_walk(array|object &$array, callable $callback, mixed $arg = null): true
Parameters
| Parameter | Description |
|---|---|
array |
The array to walk. |
callback |
function(&$value, $key, $arg); use &$value to modify elements. |
arg optional |
An extra value passed as the third argument. |
Return value
Always true.
Examples
<?php
$stock = ["tea" => 12, "cake" => 0];
array_walk($stock, function ($qty, $item) {
echo "$item: $qty\n";
});
Output
tea: 12 cake: 0
<?php
$prices = ["tea" => 3.5, "cake" => 12];
array_walk($prices, function (&$price, $item, $rate) {
$price = round($price * (1 + $rate), 2);
}, 0.2);
print_r($prices);
Output
Array
(
[tea] => 4.2
[cake] => 14.4
)Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
array.forEach()· JavaScript
Related
array_map()· Apply a callback to every element of one or more arrays and return a new array of the results.- PHP Array Functions · tutorial
- PHP Arrays · tutorial