Re: counting nested array

From: Date: Tue, 16 Aug 2005 16:21:36 +0000
Subject: Re: counting nested array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-220704@lists.php.net to get a copy of this message
On 8/16/05, Ing. Josué Aranda <josuearanda@gmail.com> wrote: > > The number of the branches is not always the same.. (it depends on the > query).. when i use count($array, COUNT_RECURSIVE) for nested arrays.. > it give to me the total including the nodes in the branches ( in this > case 28).. now here is the question, how i can get only the last nodes > in this case ... exist a easy way to do it?. or its necessary to make > a funcion with a bunch of foreach?.. any suggestions are welcome =o) > thanks! If I understand you correctly, you only want the leaves of your tree - in your example, that would be 20? I don't think there's a convenient builtin function that'll do it, but it's not hard to write your own: <?php function leaf_count($item) { $count = 0; if (!is_array($item)) { return 1; } foreach ($item as $element) { $count += leaf_count($element); } return $count; } print leaf_count($array); ?>

« previous php.general (#220704) next »