PHP 8.4.24 Released!

Voting

: max(two, three)?
(Example: nine)

The Note You're Voting On

hans at loltek dot net
1 year ago
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.

<< Back to user notes page

To Top