Reputation: 2425
I have the following array
$_POST[0][name]
$_POST[0][type]
$_POST[0][planet]
...
$_POST[1][name]
$_POST[1][type]
$_POST[1][planet]
Now i want to count all the $_POST[x][type]. How to do that?
(If i would reverse the multidimensional array, it would work i guess like this:)
$count = count($_POST['type']);
how can i count the "type" in the original structure?
Upvotes: 1
Views: 6836
Reputation: 165201
And using set operations:
$key = 'type';
$tmp = array_map($_POST, function($val) use ($key) {return isset($val[$key]);});
$count = array_reduce($tmp, function($a, $b) { return $a + $b; }, 0);
So you could reduce that down an array_filter:
$key = 'type';
$count = count(array_filter($_POST, function($val) use ($key) { return isset($val[$key]);}));
Upvotes: 0
Reputation: 197757
In your case, this works:
$count = call_user_func_array('array_merge_recursive', $_POST);
echo count($count['name']); # 2
Upvotes: 2
Reputation: 131881
PHP5.3 style
$count = array_reduce (
$_POST,
function ($sum, $current) {
return $sum + ((int) array_key_exists('type', $current));
},
0
);
Upvotes: 0
Reputation: 1250
$count = 0;
foreach ($_POST as $value) {
if (isset($value['type']) {
$count++;
}
}
Upvotes: 0
Reputation: 526593
$type_count = 0;
foreach($arr as $v) {
if(array_key_exists('type', $v)) $type_count++;
}
Upvotes: 5