function.array_count_recursive.php
Counts the number of elements in a multi-dimensional array.
An optional depth parameter specifies the level of traversal.
- Author: Aidan Lister <aidan@php.net>
- Version: 1.0.0
- Link: http://aidanlister.com/repos/v/function.array_count_recursive.php
- Views: 5814
- Downloads: 1452
Source
<?php
/**
* Counts the number of elements in a multi-dimensional array.
*
* An optional depth parameter specifies the level of traversal.
*
* @author Aidan Lister <aidan@php.net>
* @version 1.0.0
* @link http://aidanlister.com/repos/v/function.array_count_recursive.php
* @param $array array Array
* @param $depth int Depth of recursion [Default: 0 (Infinite)]
* @param $thisdepth int Must be 1 [Default: 1]
*/
function array_count_recursive($array, $depth = 0, $thisdepth = 1)
{
// End of recursion
if (!is_array($array)) {
return 1;
}
// Init
$total = 0;
// Count
if ($depth === 0 || $thisdepth < $depth) {
foreach ($array as $value) {
$total += array_count_recursive($value, $depth, $thisdepth + 1);
}
} else {
$total += count($array);
}
// Return
return $total;
}
?>
Comments