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



Question:

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


Solution:1

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


Solution:2

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


Solution:3

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


Solution:4

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;  


Solution:5

for ( $i=0 ; $i < count($arr)-1 ; $i++ )  {      echo ( $arr[$i]."," );  }  echo ( $arr[count($arr)-1] );  


Solution:6

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


Solution:7

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


Solution:8

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


Solution:9

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


Solution:10

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


Solution:11

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


Solution:12

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »