array_walk_recursive

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

Recursively walks nested arrays and calls back only on scalar leaves — contrast with array_walk (single level): the depth difference decides the use case; no direct counterpart in other languages, hand-write recursion or tree enumeration.

C C23

C23
#include <stdio.h>

/* C has no nested arrays: model a tree of leaf nodes explicitly */
typedef struct Node {
    int leaf;
    int value;
    struct Node *children[3];
    int nchild;
} Node;

static void walk_leaves(const Node *n, int *out, int *count) {
    if (n->leaf) {
        out[(*count)++] = n->value;
        return;
    }
    for (int i = 0; i < n->nchild; i++)
        walk_leaves(n->children[i], out, count);
}

int main(void) {
    Node l1 = {1, 1, {0}, 0}, l2 = {1, 2, {0}, 0}, l3 = {1, 3, {0}, 0};
    Node l4 = {1, 4, {0}, 0}, l5 = {1, 5, {0}, 0}, l6 = {1, 6, {0}, 0};
    Node n23 = {0, 0, {&l2, &l3}, 2};
    Node n56 = {0, 0, {&l5, &l6}, 2};
    Node n456 = {0, 0, {&l4, &n56}, 2};
    Node root = {0, 0, {&l1, &n23, &n456}, 3};
    int leaves[16] = {0};
    int count = 0;
    walk_leaves(&root, leaves, &count);
    for (int i = 0; i < count; i++)
        printf("%d%s", leaves[i], i + 1 < count ? "," : "\n");
    printf("count: %d\n", count);
    return 0;
}
Output
1,2,3,4,5,6
count: 6

C++ C++26

C++26
#include <iostream>
#include <variant>
#include <vector>

// C++ has no nested arrays either: model leaves/nodes with a recursive variant
struct Node;
using Tree = std::variant<int, std::vector<Node>>;
struct Node { Tree value; };

static Node leaf(int v) { Node n; n.value = Tree(v); return n; }
static Node node(std::vector<Node> children) { Node n; n.value = Tree(children); return n; }

static void walk_leaves(const Tree &t, std::vector<int> &out) {
    if (auto v = std::get_if<int>(&t)) {
        out.push_back(*v);
    } else {
        for (const Node &child : std::get<std::vector<Node>>(t))
            walk_leaves(child.value, out);
    }
}

int main() {
    std::vector<Node> tree{
        leaf(1),
        node({leaf(2), leaf(3)}),
        node({leaf(4), node({leaf(5), leaf(6)})}),
    };
    std::vector<int> leaves;
    walk_leaves(Tree(tree), leaves);
    for (size_t i = 0; i < leaves.size(); i++)
        std::cout << leaves[i] << (i + 1 < leaves.size() ? "," : "\n");
    std::cout << "count: " << leaves.size() << "\n";
    return 0;
}
Output
1,2,3,4,5,6
count: 6

C# v11.0.100

v11.0.100
// hand-rolled recursive walk over List<object>
static void WalkLeaves(object node, List<int> leaves) {
    if (node is List<object> list) {
        foreach (object child in list) WalkLeaves(child, leaves);
    } else if (node is int i) {
        leaves.Add(i);
    }
}

var tree = new List<object> { 1, new List<object> { 2, 3 },
    new List<object> { 4, new List<object> { 5, 6 } } };
var leaves = new List<int>();
WalkLeaves(tree, leaves);
Console.WriteLine(string.Join(",", leaves));
Console.WriteLine($"count: {leaves.Count}");
Output
1,2,3,4,5,6
count: 6

Go v1.27.4

v1.27.4
package main

import "fmt"

// hand-rolled recursive walk over []interface{}
func walkLeaves(node interface{}, visit func(int)) {
	switch v := node.(type) {
	case []interface{}:
		for _, child := range v {
			walkLeaves(child, visit)
		}
	case int:
		visit(v)
	}
}

func main() {
	tree := []interface{}{1, []interface{}{2, 3},
		[]interface{}{4, []interface{}{5, 6}}}
	leaves := []int{}
	walkLeaves(tree, func(v int) { leaves = append(leaves, v) })
	for i, v := range leaves {
		if i > 0 {
			fmt.Print(",")
		}
		fmt.Print(v)
	}
	fmt.Println()
	fmt.Printf("count: %d\n", len(leaves))
}
Output
1,2,3,4,5,6
count: 6

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.List;

public class Main {
    // hand-rolled recursive walk over List<Object>
    static void walkLeaves(Object node, List<Integer> out) {
        if (node instanceof List<?> list) {
            for (Object child : list) walkLeaves(child, out);
        } else if (node instanceof Integer i) {
            out.add(i);
        }
    }

    public static void main(String[] args) {
        List<Object> tree = new ArrayList<>(List.of(1,
                new ArrayList<>(List.of(2, 3)),
                new ArrayList<>(List.of(4, new ArrayList<>(List.of(5, 6))))));
        List<Integer> leaves = new ArrayList<>();
        walkLeaves(tree, leaves);
        System.out.println(leaves.toString().replace("[", "").replace("]", "").replace(" ", ""));
        System.out.println("count: " + leaves.size());
    }
}
Output
1,2,3,4,5,6
count: 6

JavaScript v26.13.1

v26.13.1
// hand-rolled recursive walk: visit every scalar leaf
function walkLeaves(node, visit) {
  if (Array.isArray(node)) {
    for (const child of node) walkLeaves(child, visit);
  } else {
    visit(node);
  }
}
const tree = [1, [2, 3], [4, [5, 6]]];
const leaves = [];
walkLeaves(tree, (v) => leaves.push(v));
console.log(leaves.join(","));
console.log("count: " + leaves.length);
Output
1,2,3,4,5,6
count: 6

PHP v8.6.0

v8.6.0
// walks leaves only: scalar values at any depth
$tree = [1, [2, 3], [4, [5, 6]]];
$leaves = [];
array_walk_recursive($tree, function ($v, $k) use (&$leaves) {
    $leaves[] = $k . ":" . $v;
});
echo implode(",", $leaves), "\n";
// contrast: array_walk visits the outer level only (3 elements)
$depth1 = 0;
array_walk($tree, function ($v) use (&$depth1) { $depth1++; });
echo $depth1, "\n";
Output
0:1,0:2,1:3,0:4,0:5,1:6
3

Python v3.15.2

v3.15.2
# hand-rolled recursive walk: visit every scalar leaf
def walk_leaves(node, visit):
    if isinstance(node, list):
        for child in node:
            walk_leaves(child, visit)
    else:
        visit(node)

tree = [1, [2, 3], [4, [5, 6]]]
leaves = []
walk_leaves(tree, leaves.append)
print(",".join(str(v) for v in leaves))
print(f"count: {len(leaves)}")
Output
1,2,3,4,5,6
count: 6

Rust v1.99.1

v1.99.1
// model the tree with a recursive enum, then walk the leaves
#[derive(Debug)]
enum Tree {
    Leaf(i32),
    Node(Vec<Tree>),
}

fn walk_leaves(t: &Tree, out: &mut Vec<i32>) {
    match t {
        Tree::Leaf(v) => out.push(*v),
        Tree::Node(children) => {
            for c in children {
                walk_leaves(c, out);
            }
        }
    }
}

fn main() {
    let tree = Tree::Node(vec![
        Tree::Leaf(1),
        Tree::Node(vec![Tree::Leaf(2), Tree::Leaf(3)]),
        Tree::Node(vec![Tree::Leaf(4),
            Tree::Node(vec![Tree::Leaf(5), Tree::Leaf(6)])]),
    ]);
    let mut leaves = Vec::new();
    walk_leaves(&tree, &mut leaves);
    let strs: Vec<String> = leaves.iter().map(|v| v.to_string()).collect();
    println!("{}", strs.join(","));
    println!("count: {}", leaves.len());
}
Output
1,2,3,4,5,6
count: 6

TypeScript v26.13.1

v26.13.1
// hand-rolled recursive walk: visit every scalar leaf
function walkLeaves(node: number | any[], visit: (v: number) => void): void {
  if (Array.isArray(node)) {
    for (const child of node) walkLeaves(child, visit);
  } else {
    visit(node);
  }
}
const tree: number | any[] = [1, [2, 3], [4, [5, 6]]];
const leaves: number[] = [];
walkLeaves(tree, (v) => leaves.push(v));
console.log(leaves.join(","));
console.log("count: " + leaves.length);
Output
1,2,3,4,5,6
count: 6

Language differences

C: no nested arrays — a struct leaf tree with explicit recursion (example); that manual modeling is exactly the essence of recursive traversal.

C++: recursive variant modeling (example); std::variant<int, vector<Node>> expresses "leaf or list of children" at the type level, safer than C's bare structs.

C#: List<object> with pattern-matching recursion (example); production code should define a strongly typed tree — the object mix just demonstrates PHP's dynamic array shape.

Go: []interface{} with a type-switch recursion (example); interface{} mixing is Go's counterpart to PHP's heterogeneous arrays, at the cost of runtime assertions.

Java: List<Object> with instanceof pattern-matching recursion (example); List.of mixing ints and lists needs the Object type due to generics.

JavaScript: Array.isArray check plus recursion (example); arrays are the built-in nested structure, no modeling needed.

PHP: array_walk_recursive calls back only on leaves (scalars) — nested arrays themselves never trigger it; the key callback receives the key within each array (inner arrays re-key from 0 in the example); versus array_walk: single-level in-place mutation vs all-depth leaf access; modifying values in the callback needs function (&$v) by reference.

Python: isinstance(list) check plus recursion (example); a fixed-depth flatten via comprehension ([x for sub in tree for x in (sub if isinstance(sub, list) else [sub])]) handles one level only — arbitrary depth still needs recursion.

Rust: recursive enum modeling (example); the Leaf/Node match recursion encodes "depth unknown" into the type system, more fundamental than dynamic checks.

TypeScript: same recursion as JavaScript (example); the number | any[] union writes leaf/node into the signature.