Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Display comma after each element except the last. Using 'for' statement and no 'implode/explode'

Tags:

arrays

loops

php

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

like image 924
Jonathan Avatar asked May 19 '10 15:05

Jonathan


1 Answers

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 ', ';
   }
}
like image 193
Tom Haigh Avatar answered Sep 22 '22 23:09

Tom Haigh