scosteve Posted October 28, 2013 Share Posted October 28, 2013 I need to echo a string of variables and depending on the input one may be empty. I have for example, $row['add_1'] = 15 north st $row['add_2'] = Apt 2 $row['city'] = Macon $row['state'] = GA echo $row['add_1'] . ", " . $row['add_2'] . ", " . $row['city'] . ", " . $row['state'] this will output 15 north st, Apt 2, Macon, GA. My problem occurs when $row['add_2'] is empty. the output looks like this. 15 north st, , Macon, GA How do I get rid of the extra comma if the variable is empty? Link to comment https://forums.phpfreaks.com/topic/283389-how-do-i-concatenate-string-with-variable-that-is-empty/ Share on other sites More sharing options...
Barand Posted October 28, 2013 Share Posted October 28, 2013 Use array_filter() to remove empty items then join/implode $row['add_1'] = '15 north st'; $row['add_2'] = ''; $row['city'] = 'Macon'; $row['state'] = 'GA'; echo join(', ', array_filter($row)); // --> 15 north st, Macon, GA edit: If the address elements are part of a larger array you can use array_slice() to extract them EG $row['name'] = 'Fred'; $row['add_1'] = '15 north st'; $row['add_2'] = ''; $row['city'] = 'Macon'; $row['state'] = 'GA'; $row['phone'] = '132 456 7890'; echo join(', ', array_filter(array_slice($row,1,4))); // --> 15 north st, Macon, GA Link to comment https://forums.phpfreaks.com/topic/283389-how-do-i-concatenate-string-with-variable-that-is-empty/#findComment-1455942 Share on other sites More sharing options...
Rifts Posted October 29, 2013 Share Posted October 29, 2013 you could just check if that variable add_2 is empty then change your code. if(empty( $row['add_2'])) { //dont include it } also issset() might work too if you want to read more about empty, isset http://techtalk.virendrachandak.com/php-isset-vs-empty-vs-is_null/ Link to comment https://forums.phpfreaks.com/topic/283389-how-do-i-concatenate-string-with-variable-that-is-empty/#findComment-1456061 Share on other sites More sharing options...
scosteve Posted October 29, 2013 Author Share Posted October 29, 2013 Thanks Rifts, I used your method. I knew that method was possible but I was hoping to avoid all the extra code. I was looking for something that worked like the trim function in access. This works though. Thanks Link to comment https://forums.phpfreaks.com/topic/283389-how-do-i-concatenate-string-with-variable-that-is-empty/#findComment-1456063 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.