I have a two dimensional array with unknown number of elements.
$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords
If I were to write a for
loop as follows, how can I determine how many rows and columns in my $two_darray
. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]
for($row=0; $row<………; $row++)
{
for($column =0; $column <………; $ column ++)
{
echo $two_darray[$row][$column];
}
echo “
end of one column
”;
}
I really need to know the value of rows and columns in order to perform other calculations.
foreach ($two_darray as $key => $row) {
foreach ($row as $key2 => $val) {
...
}
}
No need to worry about how many elements are in each array, as foreach()
will take care of it for you. If you absolutely refuse to use foreach, then just count()
each array as it comes up.
$rows = count($two_d_array);
for ($row = 0; $row < $rows; $row++) {
$cols = count($two_darray[$row]);
for($col = 0; $col < $cols; $col++ ) {
...
}
}
If you need to know an actual number, then you can use the sizeof()
or count()
functions to determine the size of each array element.
$rows = count($two_darray) // This will get you the number of rows
foreach ($two_darray as $row => $column)
{
$cols = count($row);
}
For a php Multidimensional Array, Use
$rowSize = count( $arrayName );
$columnSize = max( array_map('count', $arrayName) );
This is what i do: My superheroes' array:
$superArray[0][0] = "DeadPool";
$superArray[1][0] = "Spiderman";
$superArray[1][1] = "Ironman";
$superArray[1][2] = "Wolverine";
$superArray[1][3] = "Batman";
Get size :
echo count( $superArray ); // Print out Number of rows = 2
echo count( $superArray[0] ); // Print Number of columns in $superArray[0] = 1
echo count( $superArray[1] ); // Print Number of columns in $superArray[1] = 4
the quick way for normal,non-mixed 2-dim Array,
$Rows=count($array); $colomns=(count($array,1)-count($array))/count($array);