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

[email protected] (Richard Quadling)
Newsgroups php.general
Message-ID <[email protected]>
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). 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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.