PHP: Recursive Handling of Multidimensional Arrays

Saturday, March 14, 2009

There will be times when you find yourself with a multidimensional array and needing to perform some task across all values in it. It would be cumbersome (and in some cases impossible) to actually perform the task manually on all the elements. This is where recursion can help you. By using a recursive function, you can craft a simple function that performs the final task for you. Find the Maximum Value in a Multidimensional Array

<?php
function recursive_array_max($a) {
    foreach ($a as $value) {
        if (is_array($value)) {
            $value = recursive_array_max($value);
        }
        if (!(isset($max))) {
            $max = $value;
        } else {
            $max = $value > $max ? $value : $max;
        }
    }
    return $max;
}

$dimensional = array(
    57,
    array(3, 35),
    array(235, 534, 73, array(3, 4, 956), 6),
    14,
    2,
    array(5, 74, 73)
    );

$max = recursive_array_max($dimensional);

echo "The maximum value was: {$max}";
?>


In this case a function is created that finds the maximum value within the array. Like the built-in function max(), however, this recursive function dives deep into the array. Note the use of is_array() to detect whether each entry happens to be an array itself. If so, the function is called recursively on that array to find its maximum value. Eventually every element has been individually compared, or each array has been collapsed to its single highest value. Then the final answer is known.

Hope it helps.

0 comments: