Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

array_walk_recursive()

Visit each leaf of a nested array.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

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

Visit each leaf of a nested array. The callback receives the leaf value, its key, and optionally the user argument supplied to array_walk_recursive, in that order. The key is local rather than a full path. Array-valued nodes, including empty arrays, do not themselves reach the callback. An object stored as an element is a leaf. Receive the value by reference to edit it in place.

Signature

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

Example output

{"a":[4,6],"b":8,"empty":[]}

Examples

<?php
$tree = ['a'=>[2,3], 'b'=>4, 'empty'=>[]];
array_walk_recursive($tree, function (&$n, $key, $factor) { $n *= $factor; }, 2);
echo json_encode($tree);

Result

{"a":[4,6],"b":8,"empty":[]}

Sources