Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.