U
U
Uzair Izha2015-11-30 17:48:50
PHP
Uzair Izha, 2015-11-30 17:48:50

How to count the number of arrays in a multidimensional array?

I have a multidimensional array, it can have many arrays, how to count the number of arrays

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lesha Kiselev, 2015-11-30
@Yakud

function countArrays(array $array) {
    $count = 0;
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $count += countArrays($value) + 1;
        }
    }

    return $count;
}

$arr = [
    [ // 1
        [], // 2
        [], // 3
        [], // 4
    ],
    [ // 5
        [], // 6
        [], // 7
    ],
    [ // 8
        [], // 9
        [], // 10
        [], // 11
    ],
    [], // 12
    [], // 13
    [ // 14
        [], // 15
        [ // 16
            [], // 17
            [], // 18
        ],
    ],
];

echo countArrays($arr); // 18

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question