0

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 : enter image description here

9
  • 5
    add your sample array Commented Jan 9, 2014 at 13:10
  • 2
    Use COUNT_RECURSIVE as second parameter for count() Commented Jan 9, 2014 at 13:10
  • @almaDo why not posting an answer ? Commented Jan 9, 2014 at 13:16
  • 1
    @mb14 posting RTFM link isn't a thing that SO expects as an answer Commented Jan 9, 2014 at 13:16
  • maybe, but I'm sure SO will prefer your answer to the accepted one. Commented Jan 9, 2014 at 13:48

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

@dear downvoter can i know the reason?
if it work you should accpet my answer :)
@Awlad_Liton is this work for 3d,4d ... arrays ?
-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.
Chester: i have edited my answer for any dimensional array. @mb14 : I have edited my answer
|
1

Just count each sub-array elements.

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.