Re: Need routine to tell me number of dimensions in array.

From: Date: Tue, 16 Mar 2010 13:07:49 +0000
Subject: Re: Need routine to tell me number of dimensions in array.
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-302890@lists.php.net to get a copy of this message
On 15 March 2010 23:45, Daevid Vincent <daevid@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); arrayGetDepth($Value); --$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). Regards, 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

« previous php.general (#302890) next »