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?
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.
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.
The count() function returns the number of 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.
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
Using array_sum function
$totalarray = array_sum(array_map("count", $array));
Using Foreach Loop
$count = 0;
foreach( $array as $arrayVal){
$count += count($arrayVal);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With