-1

I have an array, print_r($badges); shows:

Array ( [0] => Array ( [0] => foobar [2] => foobar2 [4] => foobar3 ) )

I want to loop through and print all the values:

$arrlength = count($badges);

for($x=0;$x<$arrlength;$x++)
  {
  echo $badges[$x];
  echo "<br/>";
  }

But it is not working. What am I doing wrong?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • You ask *"What am I doing wrong?"* which so far is not answered: What you really do wrong is that you don't have enabled error reporting to the highest level looking for actual warnings and notices while you develop. You can highly benefit from these. See the following reference question we have on this website: [How to get useful error messages in PHP?](http://stackoverflow.com/q/845021/367456). – hakre Oct 26 '14 at 16:41
  • 1
    @hakre...not having error reporting enabled isn't "wrong". Not best practice, sure, but it has nothing to do with why the code doesn't work. – rnevius Oct 26 '14 at 16:44

3 Answers3

3

You have nested arrays. As a result, you need to target the first item of the parent array (at index [0]), and then loop through the values in the child array:

foreach ( $badges[0] as $badge ) {
    echo $badge . '<br>';
}
rnevius
  • 26,578
  • 10
  • 58
  • 86
2

Your problem is that $badges actually holds an array inside an array.

Here is the the working and simplified code:

foreach ($badges[0] as $badge) {
  echo $badge;
  echo "<br/>";
}
arkascha
  • 41,620
  • 7
  • 58
  • 90
1

You have a nested array--that is why your print_r shows a Array ( [0] => Array ( [0] =>. Additionally, you only have even-numbered keys in your array, so using for ($x = 0; $x < $arrlength; $x++) is not going to be an optimal solution. You'd be better off with foreach, which iterates through each array element. Access the inner array using $badges[0], and then iterate through it:

foreach ($badges[0] as $k => $v) {
    echo "key: $k, value: $v" . PHP_EOL;
}

Output:

key: 0, value: foobar
key: 2, value: foobar2
key: 4, value: foobar3
i alarmed alien
  • 9,412
  • 3
  • 27
  • 40