Multidimensional array in PHP

Is it possible to set an array like this

$numbers=array(array(1,2,3),array(2,3,4),array(2,3,4))

and how to loop over all elements?


Answer 1, authority 100%

Nested loops – phew!

Use recursion!

function walk_all($array){
    foreach ($array as $a) {
        if (is_array($a)) {
            walk_all($a);
        } else {
            echo $a." ";
        }
    }
}
$numbers=array(array(1,2,3),array(2,3,4),array(2,3,4));
walk_all($numbers);

Answer 2, authority 67%

Probably like this:

foreach($numbers as $v)
{
     foreach($v as $val)
     echo $val;
}

Answer 3, authority 67%

As written above or something like this

for($i=0; $i<count($numbers); $i++) {
    for($j=0; $j<count($numbers[$i]); $j++) {
         echo $numbers[$i][$j];
    }
}

UPDSo as not to eat memory 🙂

$numbersLength = count($numbers);
for( $i=0; $i<$numbersLength; $i++ )  { 
// ++$i  ,     
    $currentLength = count($number[$i]);
    for( $j=0; $j<$currentLength; $j++ ) {
         echo $numbers[$i][$j];
    }
}

When the array in the loop does not change its length, it is better to use the second option. If it changes or is unknown – it is necessary to calculate $currentLengthand possibly $numberLengthon each iteration.


Answer 4, authority 33%

array_walk_recursive

array_walk_recursive($numbers, function($val) {
    echo $val;
});