I have a multiple select list in my site where the values are inserted in a database table, in a column named available_country. I enter these values in the db separated with comma. I don't know however how to remove the last comma so it will be something like this:

USA, Europe, Asia

and not:

USA, Europe, Asia,

Here's what I tried but it didn't worked:

$sql .= "'";
foreach($_POST['available'] as $available_in) { 
	$sql .=  $available_in.", ";
}
$available_in = substr($available_in, 0, -1);

Thanks in advance.

    rtrim()

    Edit: Your code would work if you gave it the right string: "$sql", not "$available_in".

      Thanks mate. I made the change but this is what I get:

      USA, Europe, Asia, Asi

      Here's the new code:

      foreach($available as $available_in) { 
      	$sql .=  $available_in.", ";
      }
      		$sql .= substr($available_in, 0, -1);

        As Installer suggested: http://us3.php.net/manual/en/function.rtrim.php
        No need for a substr at all.

        By the way, adding lists such as these to a database is often not the best way to go about things. Makes it difficult to, for example, find all the records for Europe.

          ahundiak wrote:

          As Installer suggested: http://us3.php.net/manual/en/function.rtrim.php
          No need for a substr at all.

          By the way, adding lists such as these to a database is often not the best way to go about things. Makes it difficult to, for example, find all the records for Europe.

          Thanks man that solved my problem. One last question and I'm letting you off the hook 🙂

          Using foreach and then again using rtrim the last option from the multiple select is inserted twice in the table and what it does is trim the comma from the rtrim function. So it looks like:

          USA, Europe, Asia, Asia

          From code:

          foreach($available as $available_in) { 
          	$sql .=  $available_in.", ";
          }
          $sql .= rtrim($available_in, ",");

          I guess this is because I insert the values from muliple select in the database using foreach and then I insert again the last option from the multiple with rtrim. How can I trim the comma from the foreach function without creating duplicate entries?

            Write a Reply...