'PHP Multidimensional Array Length
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 ?
Solution 1:[1]
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);
}
?>
Solution 2:[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 .
Solution 3:[3]
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
Solution 4:[4]
// 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>";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Suyog |
| Solution 2 | |
| Solution 3 | Ninki |
| Solution 4 | Hendi Sama |
