1

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?

5 Answers 5

5
$type_count = 0;
foreach($arr as $v) {
    if(array_key_exists('type', $v)) $type_count++;
}
Sign up to request clarification or add additional context in comments.

Comments

2

In your case, this works:

$count = call_user_func_array('array_merge_recursive', $_POST);

echo count($count['name']); # 2

Comments

0
$count = 0;
foreach ($_POST as $value) {
   if (isset($value['type']) {
      $count++;
   }
}

Comments

0

PHP5.3 style

$count = array_reduce (
    $_POST,
    function ($sum, $current) {
        return $sum + ((int) array_key_exists('type', $current));
    },
    0
);

Comments

0

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]);}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.