This article brings you an introduction to the method of counting the number of multi-dimensional array elements in PHP (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Under normal circumstances, you can use count to directly count the number of elements in the array
$arr = [ 'a', 'b', ]; echo count($arr);//2
But when encountering a two-digit array, we want to count the number of elements in the second level. At this time, you can use the second parameter of the count function,
count($arr, $mode = 0);$mode(0: Count all elements in one dimension, 1: Loop count and traverse elements)
In $ When mode=1, the count function will count the number of elements in a loop. If element $a is an array, the total number will be increased by the number of elements in $a plus 1;
$arr = [ 'a' => 'b', 'c' => [ 'd', ], ]; echo count($arr, 1);//3('b',['d'],'d')
As long as the two-dimensional array has According to the rules, you can easily count the number of two-dimensional elements
$arr = [ 'a' => [ 'd', 'e', ], 'c' => [ 'd', 'g', ], ]; echo count($arr, 1) - count($arr);//4
You can also use array_map
$arrCount = 0; $countFun = function($a) use(&$arrCount) { $arrCount += count($a); return $arrCount; }; array_map($countFun,$arr); echo $arrCount;
Remember $arrCount must be passed by reference
If you want to count the number of elements of a three-dimensional array
$arr = [ 'a' => [ 'b' => [ 'd', 'e', 'g', ], ], 'c' => [ 'd' => [ 'd', 'g', ], ], ]; $arrCount = 0; $countFun = function($a) use(&$arrCount) {
$arrCount += count($a, 1) - count($a); return $arrCount; }; array_map($countFun,$arr); echo $arrCount;
If you want to count the number of elements of a four-dimensional array
$arr = [ 'a' => [ 'b' => [ 'd' => [ 'e', 'g', ], ], ], 'c' => [ 'd' => [ 'd' => [ 'e', 'g', 'f' ], ], ], ]; $arrCount = 0; $napFun = function($a) use(&$arrCount) {
$countFun = function($a) use(&$arrCount) { $arrCount += count($a, 1) - count($a); return $arrCount; }; array_map($countFun,$a); return $arrCount; }; array_map($napFun,$arr); echo $arrCount;
It is recommended to use if you want to count three dimensions or higher. Recursive method
$arr = [ 'a' => [ 'b' => [ 'd' => [ 'e', 'g', ], ], ], 'c' => [ 'd' => [ 'd' => [ 'e', 'g', 'f' ], ], ], ];
function arrCount($arr, &$arrCount, $level){ if(0 === $level){ $arrCount += count($arr); print_r($arr); }else{ $level--; foreach($arr as $a){ arrCount($a, $arrCount, $level); } } } $count = 0; $level = 3; arrCount($arr,$count,$level); echo $count;
This article has ended here. For more exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!
The above is the detailed content of Introduction to the method of counting the number of elements in multi-dimensional arrays in PHP (with code). For more information, please follow other related articles on the PHP Chinese website!