Reputation: 20845
Is there a way to find out how many value-elements are in one array in all nesting levels?
I want to find out how many are in $_REQUEST
to give out a warning if the limit dictated by the max_input_vars
directive is nearly reached?
I want to count only the real values, so array-elements should not be counted if they are another array (see http://pastebin.com/QAKxxqJf)
Upvotes: 2
Views: 838
Reputation: 26
This is my solution for PHP <= 5.2
/**
* Counts only the real values, so array-elements
* are not counted if they are another array.
*
* @param array $array
* @return int
* @author Muslim Idris
*/
function count_recursive($array) {
$count = 0;
foreach ($array as $v) {
if (is_array($v)) $count += count_recursive($v);
else $count++;
}
return $count;
}
Upvotes: 1
Reputation: 11302
Use array_walk_recursive
to count all elements that are not of type array
or object
:
$count = 0;
array_walk_recursive($a, function($v) use(&$count) {
if(!is_object($v)) ++$count; //or if(is_string($v))
});
Upvotes: 2
Reputation: 20845
I cannot use count($_REQUEST, COUNT_RECURSIVE), so I used:
function count_recursive($array) {
$count = 0;
foreach ($array as $id => $_array) {
if (is_array ($_array)) $count += count_recursive ($_array);
else $count += 1;
}
return $count;
}
$num=count_recursive($_REQUEST);
$max=ini_get('max_input_vars');
$debug=true;
if($debug and $max - $num < 50) {
echo "Warning:Number of requests ($num) is near the value of max_input_vars:$max";
}
(although there is still a strange thing is on my testing server, but thats another question: why is the number of elements in $_REQUEST smaller than the limit i set by max_input_vars? and maybe a bug in PHP)
Upvotes: 0
Reputation: 2500
check following link for all option of using count function
http://php.net/manual/en/function.count.php
Upvotes: -2
Reputation: 8528
use: count($array_name, COUNT_RECURSIVE);
as count
method takes a second argument which is the mode. int
COUNT_NORMAL
or COUNT_RECURSIVE
Upvotes: 6