Kortschot
Kortschot

Reputation: 977

Why does giving a foreach a 3-element array perform 3 iterations?

I want a comma separated list for the var $stuff:

<?php foreach($stuffs as $stuff): ?>
<?=$stuff?>
<?php endforeach; ?>

The array looks like this:

[letters] => Array
  (
    [one] => 1
    [two] => 1
    [three] => 1
  )

I tried implode but that is not working... and I don't understand why? So must be overlooking something super simple.

<?php echo implode(", ", $stuff) ?>

doesn't do a thing but,

<?php echo implode(", ", $stuffs) ?>

echo's

one, two, three, one, two, three, one, two, three

3 times. Once for every key.

Upvotes: -1

Views: 60

Answers (1)

Brian Driscoll
Brian Driscoll

Reputation: 19635

You don't need a loop if you're imploding. The implode function will do that for you. So:

<?php echo implode(", ", $stuffs) ?>

By itself, without the foreach loop, should do the trick.

Upvotes: 2

Related Questions