2

I'm trying to count the nested elements in a multidimensional array. At first I thought I could use COUNT_RECURSIVE, but that counts everything. So I've tried two different approaches, none of them appeal to me. Is there a better way to do it?

$count = 0;
foreach ($topics as $t) {
    foreach ($t as $c) {
    $count++; 
    }
}
echo $count;

// or

echo (count($topics, COUNT_RECURSIVE)-count($topics));
6
  • Your first code block does what any PHP function would have to do to get the answer you want. Commented Feb 23, 2012 at 22:01
  • You answered your own question, the second method is correct and the only method I would recommend. Commented Feb 23, 2012 at 22:02
  • I'm thinking you want to count the array elements with values, but not those with arrays in them? Also, you mention multidimensional arrays - are we talking arbitrary dimensions, or just 2? Commented Feb 23, 2012 at 22:02
  • His second code block is much faster and will always yield the same result. Commented Feb 23, 2012 at 22:03
  • Actually, I'm pretty sure the first block is the fastest. What makes you say otherwise @Mike? Commented Feb 23, 2012 at 22:05

3 Answers 3

2
function countNested($arr) {
    return (count($arr, COUNT_RECURSIVE) - count($arr));
}
Sign up to request clarification or add additional context in comments.

Comments

0

I would write this code:

$count = 0;
foreach ($topics as $t) {
    $count+= count($t); 
}
echo $count;

1 Comment

I think it count elements in two-dimensional array. I don't like the COUNT_RECURSIVE form, it is too counter intuitive for me.
0

//The following example will count either one-dimensional or two-dimensional arrays

$values_count = (count($values, COUNT_RECURSIVE) - count($values)?:count($values));

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.