Jump to content

[SOLVED] How to check if it's the last result and remove comma


t_machine

Recommended Posts

hi, I am wondering if anyone could help. I have a loop that displays my results and places a comma after each. The problem is that when the last result is displayed, it shows the comma.

 

Example:

for loop{

 

echo $row['test'].', ';

 

}

 

displays...  test1, test2, test3,

 

Notice after test3, there is still a comma? How do I remove it and have it display... test1, test2, test3

 

Thanks for any help :)

$sql = "SELECT * FROM `tbl` WHERE `this`='that'";
$res = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($res);
$x=1;

while($row = mysql_fetch-assoc($res)){
if($x == $num){
$comma = "";
}else {
$comma = ", ";
}

echo $row['text'] . $comma;
$x++;
}

The problem with adding commas after the item is that you are never sure that you have reached the last item However, you always know when you output the first.

 

So an alternative technique is to output the comma then the item unless it is the first item.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.