note 120207 added to function.count

From: Date: Tue, 22 Nov 2016 15:12:43 +0000
Subject: note 120207 added to function.count
Groups: php.notes 
Request: Send a blank email to php-notes+get-207514@lists.php.net to get a copy of this message
All the previous recursive count solutions with $depth option would not avoid infinite loops in case the array contains itself more than once. Here's a working solution: <?php /** * @param $arr * @param int $depth * @param int $i (internal) * @return int */ public static function countRecursive(&$arr, $depth = 0, $i = 1) { /** * 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/120207 Del: integrated -- https://master.php.net/note/delete/120207/integrated Del: useless -- https://master.php.net/note/delete/120207/useless Del: bad code -- https://master.php.net/note/delete/120207/bad+code Del: spam -- https://master.php.net/note/delete/120207/spam Del: non-english -- https://master.php.net/note/delete/120207/non-english Del: in docs -- https://master.php.net/note/delete/120207/in+docs Del: other reasons-- https://master.php.net/note/delete/120207 Reject -- https://master.php.net/note/reject/120207 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#207514) next »