181 of 410 menu

The array_walk Function

The array_walk function applies a given function to all elements of an array. It returns true on success or false on error. The first parameter of the function is the array, and the second is the callback.

Two parameters are passed to the callback. The first parameter is the value of the array element, and the second is the key.

The array passed to the function itself is not modified. But this can be achieved by passing the element by reference.

Syntax

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

Example

Let's iterate through the array and output its keys and elements:

<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3]; array_walk($arr, function($elem, $key) { echo $key . ' ' . $elem . '<br>'; }); ?>

Code execution result:

'a 1' 'b 2' 'c 3'

Example

Let's iterate through the array and square its elements:

<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3]; array_walk($arr, function(&$elem, $key) { $elem = $elem ** 2; }); var_dump($arr); ?>

Code execution result:

['a' => 1, 'b' => 4, 'c' => 9]

See Also

byenru