8

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
  • 1
    Tom Haigh's answer should work. Or just remove the last character from your resulting string (but might be not such a clean way ;)). Commented May 19, 2010 at 15:13
  • @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). Commented May 19, 2010 at 15:30
  • @Felix: because of the ridiculous condition not to use implode Commented May 19, 2010 at 15:32
  • @SilentGhost: See my previous comment, I think you judge too fast... Commented May 19, 2010 at 15:34
  • @felix: use of implode would be appropriate here, I don't see why the question needs to be limited by some unreasonable conditions. Commented May 19, 2010 at 15:37

12 Answers 12

13

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 ', ';
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

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: wouldn't that still give you a trailing comma?
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";}
5

A better solution is to avoid looping altogether. I've ignored building the links for the sake of clarity. Note that I don't believe the inability to use implode is a condition. I believe it's a simple statement of, "I can't see how to make this work using implode, so I did it this way instead."

$last_entry = array_pop($director);
if(count($director) > 0) {
    echo implode(", ", $director) . " and " . $last_entry;
} else {
    echo $last_entry;
}

Comments

4

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, ", ");

1 Comment

You can even rtrim() rather than trim(), so you definitely only catch trailing commas.
2

My preferred method:

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

Or

$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;

1 Comment

I tend to use this one too! :-) Nice.
1
for ( $i=0 ; $i < count($arr)-1 ; $i++ )
{
    echo ( $arr[$i]."," );
}
echo ( $arr[count($arr)-1] );

Comments

0
$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.

Comments

0

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 ',';}
}

Comments

0

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>';
}

Comments

0
// RENAMED $director to $directors

$links = '';
foreach ($directors AS $director) {
    $links .= "<a href=\"person.php?id={director['id']}\">{$director['name']}</a>";
    if (true !== empty($links)) {
        $links .= ', ';
    }
}

echo $links;

Comments

0
foreach ($strings as $string){
    $superstring .= $string . ', ';
}
$echostring = substr_replace($superstring ,"",-2);
echo $echostring;

Comments

0

Here's my 2 lines solution

// Create your Array
$cities = Array("Rome", "Florence", "Venice");

// implode them
$list = trim(implode (", ", $cities))  ;
// remove last comma
$list = substr ( $list,0 ,strlen( $list ) );

//check result
die ($list);

Comments

-1

$count =1;
for ($i = 0; $i < count($director); $i++) {
if ($count!=1) {
echo ' , ';
}
echo ''.$director[$i]["name"].'';
$count++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.