note 130141 added to function.array-walk-recursive
| From: | hans@loltek.net | Date: | Thu, 13 Mar 2025 14:52:15 +0000 |
| Subject: | note 130141 added to function.array-walk-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221971@lists.php.net to get a copy of this message | ||
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; // just mimicking array_walk_recursive
}
?>
Useful if you have large array-and-object soup in production code.
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 62.101.231.203)
----
Manual Page -- https://php.net/manual/en/function.array-walk-recursive.php
Edit -- https://main.php.net/note/edit/130141
Del: integrated -- https://main.php.net/note/delete/130141/integrated
Del: useless -- https://main.php.net/note/delete/130141/useless
Del: bad code -- https://main.php.net/note/delete/130141/bad+code
Del: spam -- https://main.php.net/note/delete/130141/spam
Del: non-english -- https://main.php.net/note/delete/130141/non-english
Del: in docs -- https://main.php.net/note/delete/130141/in+docs
Del: other reasons-- https://main.php.net/note/delete/130141
Reject -- https://main.php.net/note/reject/130141
Search -- https://main.php.net/manage/user-notes.php