PHP Count values of an array
Is there a way to count the values of 开发者_如何学JAVAa multidimensional array()?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
So for instance, I'd want to count the 3 values within the array "Test"... ('test1', 'test2', 'test3')?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
echo count($families["Test"]);
I think I've just come up with a rather different way of counting the elements of an (unlimited) MD array.
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function() { global $i; return ++$i; });
echo $i;
?>
Perhaps not the most economical way of doing the count, but it seems to work! You could, inside the anonymous function, only add the element to the counted total if it had a non empty value, for example, if you wanted to extend the functionality. An example of something similar could be seen here:
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function($value, $key) { global $i; if ($value == 'gh') ++$i; });
echo $i;
?>
The count method must get you there. Depending on what your actual problem is you maybe need to write some (recursive) loop to sum all items.
A static array:
echo 'Test has ' . count($families['test']) . ' family members';
If you don't know how long your array is going to be:
foreach($families as $familyName => $familyMembers)
{
echo $familyName . ' has got ' . count($familyMembers) . ' family members.';
}
function countArrayValues($ar, $count_arrays = false) {
$cnt = 0;
foreach ($ar as $key => $val) {
if (is_array($ar[$key])) {
if ($count_arrays)
$cnt++;
$cnt += countArrayValues($ar);
}
else
$cnt++;
}
return $cnt;
}
this is custom function written by me, just pass an array and you will get full count of values. This method wont count elements which are arrays if you pass second parameter as false, or you don't pass anything. Pass tru if you want to count them also.
$count = countArrayValues($your_array);
精彩评论