Example 1 — Sum All Nested Numbers
Add up every number in a nested array.
<?php
$data = [1, [2, 3], [4, [5]]];
$total = 0;
array_walk_recursive($data, function ($value) use (&$total) {
$total += $value;
});
echo "Total: ", $total, PHP_EOL; How It Works
- The array has numbers at different nesting levels.
- use (&$total) lets the callback update the outside variable.
- array_walk_recursive() walks into each inner array and calls the callback for every number.
- 1 + 2 + 3 + 4 + 5 equals 15.

