Amit Rajput
Amit Rajput

Reputation: 2059

How to count number of elements of a multidimensional array without using loop in PHP?

I have a an array like below:

$array = Array
        (
            '0' => Array
                (
                    'num1' => 123,
                    'num2' => 456,
                ),
            '1' => Array
                (
                    'num3' => 789,
                    'num4' => 147,
                ),
            '2' => Array
                (
                    'num5' => 258,
                    'num6' => 369,
                    'num7' => 987,
                ),
        );

I want to count number of elements i.e. from num1 to num7 means I want output 7. How can i do this without using loop?

Upvotes: 4

Views: 1491

Answers (3)

mickmackusa
mickmackusa

Reputation: 48001

From the standpoint of time complexity, a good functional iterator to only loop over the data once and directly return the total count is array_reduce().

Code: (Demo)

echo array_reduce($array, fn($total, $row) => $total + count($row));
// 7

Upvotes: 0

Chetan Ameta
Chetan Ameta

Reputation: 7896

use array_sum and array_map function together.

try below solution:

$array = Array
(
    '0' => Array
    (
        'num1' => 123,
        'num2' => 456,
    ),
    '1' => Array
    (
        'num3' => 789,
        'num4' => 147,
    ),
    '2' => Array
    (
        'num5' => 258,
        'num6' => 369,
        'num7' => 987,
    ),
);

echo $total = array_sum(array_map("count", $array));

output

7

alternat way can be:

echo count($array, COUNT_RECURSIVE) - count($array); //output: 7

Upvotes: 5

Ritesh d joshi
Ritesh d joshi

Reputation: 823

Using array_sum function

$totalarray = array_sum(array_map("count", $array));

Using Foreach Loop

$count = 0;
foreach( $array as $arrayVal){
    $count += count($arrayVal);
}

Upvotes: 2

Related Questions