views:

299

answers:

6

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

+7  A: 

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 ', ';
   }
}
Tom Haigh
Everyone always does this by checking `$i < ($count - 1);`; am I the only person who moves the check above the main echo and checks for `$i != 0`?
Michael Mrozek
@Michael Mrozek: wouldn't that still give you a trailing comma?
Tom Haigh
No, you're adding leading commas instead of trailing, but it skips the first so you don't get ", stuff, stuff". `for(...) {if($i != 0) {echo ", ";} echo "stuff";}`
Michael Mrozek
A: 
$number = count($director);
for ($i = 0; $i < $number; $i++) {
    echo '<a href="person.php?id='.$director[$i]["id"].'">'.$director[$i]["name"].'</a>';
    if($i < $number - 1){
        echo ', ';
    }
}

Oops, I didn't saw the reply by Tom Haigh, we came with practically the same.

Adirael
A: 

How about something like this? You may want to store the result of "count($director)" in a variable outside the loop so that you do not have to waste resources recalculating it each time the loop is run.

for($i=0; $i<count($director);$i++){
   echo '<a href="person.php?id='.$director[$i]["id"].'">'.$director[$i]["name"].'</a>';
   if($i!=count($director)-1){echo ',';}
}
jeremysawesome
+2  A: 

My preferred method:

$output = "";
for ($i = 0; $i < count($director); $i++) {
  if ($output) {
    $output .= ", ";
  }
  $output .= '<a href="person.php?id='.$director[$i]["id"].'">'.$director[$i]["name"].'</a>';
}
echo $output;
Matt S
I tend to use this one too! :-) Nice.
acmatos
+2  A: 

If I remember PHP syntax correctly, this might also help:

$str = "";
for ($i = 0; $i < count($director); $i++) {
   $str .= '<a href="person.php?id='.$director[$i]["id"].'">'.$director[$i]["name"].'</a>, ';
}
$str = trim($str, ", ");
hudolejev
You can even `rtrim()` rather than `trim()`, so you definitely only catch trailing commas.
pinkgothic
A: 

Well, foreach contains for :-)

foreach ($director as $key => $person) {
    if ($key !== 0) echo ', ';
    echo '<a href="person.php?id='.urlencode($person['id']).'">'.$person['name'].'</a>';
}
salathe