Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
Amit Rajput Avatar asked Apr 11 '16 05:04

Amit Rajput


People also ask

How do you calculate the total number of elements in a multidimensional array in PHP?

The length of the array can be counted by iterating the array values through the loop and by using PHP built-in functions. The count() and sizeof() functions are used to count the length of an array in PHP. The ways to count the length of PHP arrays by using these functions are shown in this tutorial.

How do you determine the number of elements in a multidimensional array?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

How do I count the number of elements in an array PHP?

The count() function returns the number of elements in an array.

How do you count all the elements in an array?

The count() and sizeof() both functions are used to count all elements in an array and return 0 for a variable that has been initialized with an empty array. These are the built-in functions of PHP. We can use either count() or sizeof() function to count the total number of elements present in an array.


2 Answers

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
like image 62
Chetan Ameta Avatar answered Nov 15 '22 00:11

Chetan Ameta


Using array_sum function

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

Using Foreach Loop

$count = 0;
foreach( $array as $arrayVal){
    $count += count($arrayVal);
}
like image 31
Ritesh d joshi Avatar answered Nov 14 '22 23:11

Ritesh d joshi