Remove the last character from a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wbryan6
Forum Newbie
Posts: 22
Joined: Sat Feb 04, 2006 12:13 pm

Remove the last character from a string

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

you can use substr() to do that, alternatively you should be using implode() for this kind of thing
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post 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
Post Reply