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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 





Richard Quadling wrote:
On 15 March 2010 23:45, Daevid Vincent <daevid@xxxxxxxxxx> 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

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux