note 120209 added to function.count

From: Date: Tue, 22 Nov 2016 16:32:31 +0000
Subject: note 120209 added to function.count
Groups: php.notes 
Request: Send a blank email to php-notes+get-207516@lists.php.net to get a copy of this message
There was a small bug in the previous comment. Fixed version: <?php /** * Recursively count elements in an array. Behaves exactly the same as native * count() function with the $depth option. Meaning it will also add +1 to the * total count, for the parent element, and not only counting its children. * @param $arr * @param int $depth * @param int $i (internal) * @return int */ public static function countRecursive(&$arr, $depth = 0, $i = 0) { $i++; /** * In case the depth is 0, use the native count function */ if (empty($depth)) { return count($arr, COUNT_RECURSIVE); } $count = 0; /** * This can occur only the first time when the method is called and $arr is not an array */ if (!is_array($arr)) { return count($arr); } // if this key is present, it means you already walked this array if (isset($arr['__been_here'])) { return 0; } $arr['__been_here'] = true; foreach ($arr as $key => &$value) { if ($key !== '__been_here') { if (is_array($value) && $depth > $i) { $count += self::countRecursive($value, $depth, $i); } $count++; } } // you need to unset it when done because you're working with a reference... unset($arr['__been_here']); return $count; } ?> ---- Server IP: 72.52.91.14 Probable Submitter: 95.65.108.24 ---- Manual Page -- http://php.net/manual/en/function.count.php Edit -- https://master.php.net/note/edit/120209 Del: integrated -- https://master.php.net/note/delete/120209/integrated Del: useless -- https://master.php.net/note/delete/120209/useless Del: bad code -- https://master.php.net/note/delete/120209/bad+code Del: spam -- https://master.php.net/note/delete/120209/spam Del: non-english -- https://master.php.net/note/delete/120209/non-english Del: in docs -- https://master.php.net/note/delete/120209/in+docs Del: other reasons-- https://master.php.net/note/delete/120209 Reject -- https://master.php.net/note/reject/120209 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#207516) next »