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

From: Date: Tue, 16 Mar 2010 14:46:11 +0000
Subject: Re: Need routine to tell me number of dimensions in array.
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-302893@lists.php.net to get a copy of this message
Richard Quadling wrote:
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).
Using a reference actually increases overhead. References in PHP were mostly useful in PHP4 when assigning objects would cause the object to be copied. But even then, for arrays, a Copy on Write (COW) strategy was used (and is still used) such that you don't copy any values. Try it for yourself: <?php $copies = array(); $string = str_repeat( '*', 1000000 ); echo memory_get_usage()."\n"; for( $i = 0; $i < 1000; $i++ ) {
    $copies[] = $string;
} echo memory_get_usage()."\n"; ?> Cheers, Rob. -- http://www.interjinn.com Application and Templating Framework for PHP

« previous php.general (#302893) next »