13

This is a multidimensional PHP array.

$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);

I can find out the length of the array. That means

count($stdnt); // output is 4

[
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94)
] ` 

But can't get the internal array length.

How can I ?

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
Arafat Rahman
  • 993
  • 5
  • 19
  • 46

5 Answers5

13

If you are assuming the subarrays are all the same length then:

$count = count($stdnt[0]);

If you don't know the keys:

$count = count(reset($stdnt));

To get an array with a separate count of each of the subarrays:

$counts = array_map('count', $stdnt);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
6

The other way to count internal array lengths is to iterate through the array using foreach loop.

<?php 
$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);

foreach($stdnt as $s)
{
    echo "<br>".count($s);
}
?>  
Suyog
  • 2,472
  • 1
  • 14
  • 27
2

please use sizeof function or count function with recursive

 e.g echo (sizeof($stdnt,1) - sizeof($stdnt)) ; // this will output you 9 as you want .

first sizeof($stdntt,1) ; // will output you 13 . count of entire array and 1 mean recursive .

Affan
  • 1,132
  • 7
  • 16
1

According to the hint from Meaning of Three dot (…) in PHP, the following code is what I usually use for this case:

$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);
echo count(array_merge(...$stdnt));

The Splat operator "..." will only work,

  • Only if the first level keys are in integer, ie, not "strings"
  • PHP > 5.6
Ninki
  • 93
  • 2
  • 8
0
  // You may try as per this sample  

  $cars=array(
    array("volvo",43,56),
    array("bmw",54,678)
  );
  $mySubSize=sizeof($cars);
  for ($i=0;$i<$mySubSize;$i++) {
    foreach ($cars[$i] as $value) {
      echo "$value <br>";
    }
  }
  • It would be nice if you could explain how your code works. There is a bit too much code here for others to copy-paste confidently without understanding it in depth! – Simas Joneliunas Feb 09 '22 at 04:57