3
I have a matrix and I need to know how to do the foreach
and know the total size of the matrix.
$matriz = array();
$matriz[0][1] = '01';
$matriz[0][2] = '02';
$matriz[1][1] = '11';
$matriz[1][2] = '12';
3
I have a matrix and I need to know how to do the foreach
and know the total size of the matrix.
$matriz = array();
$matriz[0][1] = '01';
$matriz[0][2] = '02';
$matriz[1][1] = '11';
$matriz[1][2] = '12';
3
To walk the array
, which is multidimensional, it is also necessary to cover the subarrays:
$matriz = array();
$matriz[0][1] = '01';
$matriz[0][2] = '02';
$matriz[1][1] = '11';
$matriz[1][2] = '12';
foreach ($matriz as $itens) {
foreach ($itens as $item) {
echo $item . "\n";
}
}
To know the total of items, you can use the count
, but because it is a array
multidimensional, use count
together with the array_map
, so will return the amount of items that each subarray has, to add them, use the array_sum
:
echo "Total: " . array_sum(array_map("count", $matriz)) . "\n"; // 4
Browser other questions tagged php
You are not signed in. Login or sign up in order to post.