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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_walk(array|object &$array, callable $callback, mixed $arg = null): true

Parameters

ParameterDescription
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

Visit keys and valuesTry it yourself
<?php
$stock = ["tea" => 12, "cake" => 0];
array_walk($stock, function ($qty, $item) {
    echo "$item: $qty\n";
});

Output

tea: 12
cake: 0
Change values in placeTry it yourself
<?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

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?