Count all indexes on multi-dimension arrays

Last modified date

Comments: 0

Following on from my initial I didn’t know PHP did that! post yesterday, it wasn’t long before I had my next realisation about PHP; this time with a simple little parameter to the count function that I didn’t know existed.

Everyone knows how to use count, right? It’s super handy in all kinds of circumstances.


$a = [1, 2, 3, 4, 5];
echo count($a); // 5

And, I would hedge bets, that for most people that’s all they know it can do.

What if you have this?

$a = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12]

If you did a count($a) on that you’d end up with 3. For the most part you think, “ok, it’s got three arrays in the array, that checks”. But what if you wanted to count how many indexes it has including the indexes in the children?

I’d imagine some people might go down the lines of something like:


$total = 0;
foreach ($a as $k => $v) {
    $total += count($v) + 1; // +1 because of the $k index you're on

Well, OK, but that’ll get messy quickly if you have sub-sub arrays, and you should always be putting in checks for types to be safe… urgh. Messy.

That’s where the second parameter to count, erm.. counts. It’s the count mode and can be either COUNT_NORMAL or COUNT_RECURSIVE – and it’s the latter you want to use.

echo count($a, COUNT_RECURSIVE); // 15


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.