note 120209 deleted from function.count by sobak
| From: | sobak@php.net | Date: | Wed, 23 Nov 2016 02:56:13 +0000 |
| Subject: | note 120209 deleted from function.count by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-207520@lists.php.net to get a copy of this message | ||
Note Submitter: php_count at cubmd dot com
----
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;
}
?>