-1

I tried to use a foreach loop on a multi-dimensional array, and found out that it didn't exactly worked out the way that I expected. Is there a foreach loop for multi-dimensional arrays, or another way to do this?

$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";

foreach($array as $a) {

    echo $a."<br>";

}

Result:

Nothing

Needed Result:

a
b
c
frosty
  • 2,559
  • 8
  • 37
  • 73

5 Answers5

2

You could also try this:

 foreach($array[0] as $key => $value){
   echo $value . "<br>":
  }

$array in this code you're accessing the key of 0,0,0 so it will not print it.

$array[0] in this code you're both accessing key 0,1,2 and the values a,b and c

aldrin27
  • 3,407
  • 3
  • 29
  • 43
1

You need two loops. One to loop the first array, and one to loop the inner one.

foreach($array as $key) {
   foreach($key as $val) {
       echo $val;
    }
}
devlin carnate
  • 8,309
  • 7
  • 48
  • 82
  • It all depends on how many layers the multi-dimensional array has, right? So, three layers would need three loops, yes? – frosty Oct 15 '15 at 20:47
  • @frosty - yes. If you don't know the number of layers, you could use a [recursive loop](http://stackoverflow.com/questions/10928993/is-there-a-way-to-loop-through-a-multidimensional-array-without-knowing-its-dep). – devlin carnate Oct 15 '15 at 21:13
1

Try nesting another foreach...

$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";

foreach($array as $a) {
  foreach($a as $val){
    echo $val."<br>";
  }
}
Steve Perry
  • 556
  • 4
  • 11
1

It is because $a is still an array. If you use print_r() you will see this:

foreach($array as $a) {

    print_r($a);

}

Result:

Array
(
    [0] => a
    [1] => b
    [2] => c
)

To combat the nested array you have to run a second foreach() loop to get the values:

foreach($array as $a) {

    foreach($a as $value){ // loop through second array
        echo $value . "</ br>";
    }

}
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
1

well since no one else has mentioned it:

<?php
$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";


echo implode('<br>',$array[0]);

http://codepad.viper-7.com/SC9PLI