PHP - using a recursive function to find the max() of nested arrays

后端 未结 2 1616
北海茫月
北海茫月 2021-01-25 17:11

The following code uses a simple strategy for finding the max of the nested array. It uses foreach to find and label the max value, however, if I got an array that was nested t

2条回答
  •  耶瑟儿~
    2021-01-25 17:44

    You can use array_walk_recursive() for it:

    function array_max_recursive($arr)
    {
        $max = -INF;
    
        array_walk_recursive($arr, function($item) use (&$max) {
            if ($item > $max) {
                $max = $item;
            }
        });
    
        return $max;
    }
    
    echo array_max_recursive(["1", "2", ["3", "4"]]); // 4
    

提交回复
热议问题