Schlo_50 Posted June 3, 2008 Share Posted June 3, 2008 Hi guys, I have 6 variables which need to be placed into a string, each separated by commas. I can do that, BUT, sometimes not all of the variables will have a value so when I print my string I get something like the following: var1, var2, , var4, var5, var6 I have tried to use str_replace to get a nice comma separated list without a comma at the end of the last number but it's not really working well. Has anybody got any ideas as to how I can code this please? My example code follows: $relevant = "1a"; $relevant_two = "2b"; $relevant_three = "3c"; $relevant_four = ""; $relevant_five = "5e"; $relevant_six = "6f"; $strt_string = "$relevanta, $relevantb, $relevantc, $relevantd, $relevante, $relevantf"; $srt_string = str_replace(' ,', '', $strt_string); Thanks in advance! Link to comment https://forums.phpfreaks.com/topic/108514-solved-preg-str_replace/ Share on other sites More sharing options...
DarkWater Posted June 3, 2008 Share Posted June 3, 2008 Put them all in an array and do: foreach ($relevant as $v) { if (!is_null($v)) { $strt_string .= $v; } } Link to comment https://forums.phpfreaks.com/topic/108514-solved-preg-str_replace/#findComment-556373 Share on other sites More sharing options...
samshel Posted June 3, 2008 Share Posted June 3, 2008 Simplest way $arrString = array(); $arrString[] = "1a"; $arrString[] = "2b"; $arrString[] = "3c"; $arrString[] = ""; $arrString[] = "5e"; $arrString[] = "6f"; $strString = implode(",", $arrString); Link to comment https://forums.phpfreaks.com/topic/108514-solved-preg-str_replace/#findComment-556400 Share on other sites More sharing options...
Schlo_50 Posted June 3, 2008 Author Share Posted June 3, 2008 Thanks Link to comment https://forums.phpfreaks.com/topic/108514-solved-preg-str_replace/#findComment-556428 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.