Foreach for array

3

I have an array and I need to know how I can do foreach and know the total size of the array.

$matriz = array();

$matriz[0][1] = '01';
$matriz[0][2] = '02';
$matriz[1][1] = '11';
$matriz[1][2] = '12';
    
asked by anonymous 25.10.2016 / 00:26

1 answer

3

To go through the array , which is multidimensional, you must also go through 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";
    }
}

For total items, you can use count , but because it is of a% multidimensional%, use array in conjunction with count , so will return the amount of items each subarray has, to sum them up, use array_map :

echo "Total: " . array_sum(array_map("count", $matriz)) . "\n"; // 4

See DEMO

    
25.10.2016 / 00:40