On 15 March 2010 23:45, Daevid Vincent <dae...@daevid.com> wrote:
> Anyone have a function that will return an integer of the number of
> dimensions an array has?

 * Get the maximum depth of an array
 * @param array &$Data A reference to the data array
 * @return int The maximum number of levels in the array.
function arrayGetDepth(array &$Data) {
        static $CurrentDepth = 1;
        static $MaxDepth = 1;

        array_walk($Data, function($Value, $Key) use(&$CurrentDepth, 
&$MaxDepth) {
                if (is_array($Value)) {
                        $MaxDepth = max($MaxDepth, ++$CurrentDepth);

        return $MaxDepth;

Extending Jim and Roberts comments to this. No globals. By using a
reference to the array, large arrays are not copied (memory footprint
is smaller). And by using array_walk, a separate internal pointer is
used, so no need to worry about losing your position on the array.

Something to watch out for though is recursion in the array. If a
value in the array is a reference to another part of the array, you
are going to loop around for ever.

$Data = array(&$Data);

for example, with the line ...

                echo "$CurrentDepth, $MaxDepth, $Key\n";

in the callback function() will report 17701 before crashing out (no
stack error surprisingly enough).


Richard Quadling.

Richard Quadling
"Standing on the shoulders of some very clever giants!"
EE : http://www.experts-exchange.com/M_248814.html
EE4Free : http://www.experts-exchange.com/becomeAnExpert.jsp
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling

PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to