Re: counting nested array

From: Date: Wed, 17 Aug 2005 09:04:39 +0000
Subject: Re: counting nested array
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-220738@lists.php.net to get a copy of this message
On 8/17/05, Ing. Josué Aranda <josuearanda@gmail.com> wrote: > OK this the little function i made to solve this.. > > function countNested($array){ > foreach($array as $value){ > if(is_array($value)) > $total=$this->countNested($value)+$total; > }else{ > $total=$total+1; > } > } > return $total; > } Looks OK-ish - there's a missing '{' on the third line but apart from that it should work fine as a class method. > any optimizations are welcome.... You can simplify the if-block as below, which might save you as much as a microsecond or two :-) function countNested($array){ $total = 0; foreach ($array as $value) { $total += is_array($value) ? $this->countNested($value) : 1; } return $total; }

« previous php.general (#220738) next »