If you want to iterate both arrays and objects interchangeably:
<?php
function array_and_object_walk_recursive(array|object &$array, callable $callback, mixed $arg = null): true
{
$argumentCount = func_num_args();
if ($argumentCount > 3) {
throw new \ArgumentCountError("array_and_object_walk_recursive() expects at most 3 arguments, $argumentCount given");
}
$hasThirdArgument = ($argumentCount === 3);
foreach ($array as $key => &$value) {
if (is_array($value) || is_object($value)) {
if ($hasThirdArgument) {
array_and_object_walk_recursive($value, $callback, $arg);
} else {
array_and_object_walk_recursive($value, $callback);
}
}
if ($hasThirdArgument) {
($callback)($value, $key, $arg);
} else {
($callback)($value, $key);
}
}
return true; }
?>
Useful if you have large array-and-object soup in production code.