I have this simple for loop to echo an array:

for ($i = 0; $i < count($director); $i++) {
   echo '<a href="person.php?id='.$director[$i]["id"].'">'.$director[$i]["name"].'</a>';

The problem here is that when more than one element is in the array then I get everything echoed without any space between. I want to separate each element with a comma except the last one.

I can't use implode so I'm looking for another solution


Tom Haigh's answer should work. Or just remove the last character from your resulting string (but might be not such a clean way ;)).

Written by Felix Kling

@SilentGhost: Why did you tag this homework? If because of the statement I cant use 'implode' : The OP accesses an array so he needs the loop. implode only works when you have already an array of elements to "implode" (of course one could generate a list of the HTML beforehand and then implode but this seems unnecessary to me).

Written by Felix Kling

@Felix: because of the ridiculous condition not to use implode

Written by SilentGhost

@SilentGhost: See my previous comment, I think you judge too fast...

Written by Felix Kling

@felix: use of implode would be appropriate here, I don't see why the question needs to be limited by some unreasonable conditions.

Written by SilentGhost

@Silent I think he's right, this isn't homework, the OP just doesn't want to make an array so he can implode it, he prefers a for loop

Written by Michael Mrozek

I don't find the condition ridiculous, but I do think it might be worth re-considering, e.g. foreach ($directors as $key => $director) { $directors[$key] = '<...>' . $director['name'] . '</...>'; } echo implode(', ', $directors);. Since the OP expressly asked not to use implode(), I'm not putting it as an answer, but it might help someone else stumbling across this question.

Written by pinkgothic

Accepted Answer

This should work. It's better I think to call count() once rather than on every loop iteration.

$count = count($director);
for ($i = 0; $i < $count; $i++) {
   echo '<a href="person.php?id='.$director[$i]["id"].'">'.$director[$i]["name"].'</a>';

   if ($i < ($count - 1)) {
      echo ', ';
Written by Tom Haigh
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki