Re: [PHP] Need routine to tell me number of dimensions in array.
[email protected] (Robert Cummings)
| Newsgroups | php.general |
|---|---|
| Organization | InterJinn |
| Message-ID | <[email protected]> |
Richard Quadling wrote: > On 15 March 2010 23:45, Daevid Vincent <[email protected]> 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