Page 1 of 1

Remove the last character from a string

Posted: Wed Jul 05, 2006 4:32 pm
by wbryan6
I am trying to unravel a string and place it into an Insert Query like so:

Code: Select all

foreach($array as $value)
{
     $insert .= " '$value', ";
}
The problem is that because a I have to have a comma to seperate each entry into my Insert query, I have an extra comma at the end (ie ( '$value', ) which won't execute properly. Unfortunately, additional looping structure is not an option. Is there anyway to trip this last comma off the string? Thanks.

Posted: Wed Jul 05, 2006 4:36 pm
by John Cartwright
you can use substr() to do that, alternatively you should be using implode() for this kind of thing

Posted: Wed Jul 05, 2006 4:57 pm
by printf
Or better yet, just remove the foreach() all together

Code: Select all

$insert = "'" . implode ( "', '", $array ) . "'";

mysql_query ( "INSERT INTO my_table VALUES ( " . $insert . " );");

pif