I want to know how do I count total number of matrix elements? the count() function tells me the number of elements of an array, but if i have m[n][n], how do i know how many elements are there? thx
This is the result of var_dump : 
3 Answers
EDIT:
For any dimensional Array count of elements:
Demo : https://eval.in/87683
$food = array('fruits' => array('orange', 'banana', 'apple'),"dsd"=>array('orange', 'banana', 'apple','dsfdsf'),'sa'=>array('1','1','1','1','1','1','1','1','1','1','1'));
$arr = (array_map('count', $food));
//print_r($arr);
$c = 0;
foreach($arr as $k => $v){
$c += $v;
}
echo $c;
Max array count: Live demo :https://eval.in/87611
echo max(array_map('count', $your2dArray));
It will return count of 2d array
If you want to get count of the all the elements then :
$array[0][0] = "one";
$array[0][1] = "two";
$array[1][0] = "three";
$array[1][1] = "four";
$c=0;
foreach($array as $a){
$c =$c+count($a);
}
echo $c;
Live demo : https://eval.in/87617
6 Comments
Awlad Liton
@dear downvoter can i know the reason?
Awlad Liton
if it work you should accpet my answer :)
Attila Naghi
@Awlad_Liton is this work for 3d,4d ... arrays ?
mb14
-1 because max(array_map('count' ...) doesn't work. In your second examples it would return 2. Your "first" live demo only work because you have one line.
Awlad Liton
Chester: i have edited my answer for any dimensional array. @mb14 : I have edited my answer
|
This does work for 2d, 3d, 4d Arrays:
$myArray = array(array(1,2,3,4,5), array(6,7), array(array(8,9)));
$countRec = count($myArray, COUNT_RECURSIVE);
print $countRec;
But this returns 13 as the result since it is counting: Elements in 1st Depth + Elements in 2nd depth ...
So it's calculation is: 2 + 8 + 1 + 2 = 13
COUNT_RECURSIVEas second parameter forcount()