Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_walk() function

Reference for PHP array_walk(): run a callback on every element with its key, modify values by reference, pass extra data, and know when to use map instead.

array_walk() calls a function for each element of an array, passing the value and the key. Unlike array_map(), it works on the original array and is meant for side effects or in-place changes: if the callback takes the value by reference, assignments to it change the array itself.

The function returns true and does not build a new array. This makes it the right tool when you want to update an array where it stands, or print or collect something for each element.

PHP
<?php
$a = [1, 2, 3];
array_walk($a, function (&$v) { $v *= 2; });
// $a is [2, 4, 6]

Try it

PHP Changing values in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Side effects and nested arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

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

The callback is called as callback(&$value, $key) or, if $arg is given, callback(&$value, $key, $arg).

Name Description
&$array The array (or object) to walk, passed by reference.
$callback Receives each value (declare it &$value to modify the array) and its key.
$arg Optional. An extra value passed as the third parameter of every call.

Return value: always true in current PHP versions (older versions documented bool).

Usage notes

  • Take the value by reference to change it: function (&$v, $k). Without the &, the callback works on a copy and the array stays unchanged.
  • Only values change. You cannot rename keys or remove elements from inside the callback; build a new array with a foreach loop or array_filter() for that.
  • Not recursive. Nested arrays arrive as plain array values. Use array_walk_recursive() to reach every leaf.
  • To transform into a new array, prefer array_map(), which leaves the input alone and returns the result.
  • Callback parameter count: if the callback requires more parameters than array_walk() provides, PHP throws an ArgumentCountError. Built-in functions with required extra parameters can fail this way.
  • Do not add or delete elements of the array inside the callback; the behavior is undefined.
  • Plain loop alternative: foreach ($a as $k => &$v) does the same job and is easier to debug; remember to unset($v) afterwards.