Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Display comma after each variable if variable is not empty

Tags:

php

How to display comma after each variable only if that variable is not empty.

<?php echo $City; ?>, <?php echo $Province(); ?>, <?php echo $PostalCode(); ?>, <?php echo $Country(); ?>
like image 682
user3351236 Avatar asked Apr 29 '15 07:04

user3351236


1 Answers

Another way would be to put them inside an array in conjunction with array_filter to clean out empty strings and implode them:

$vars = array_filter(array($City, $Province, $PostalCode, $Country));
echo implode(',', $vars);

Sidenote: If you want to treat empty spaces also, you could map out trim on elements, then filter:

$test = array_filter(array_map('trim', array('1', ' ', 'test')));
                                              //   ^ single space
like image 106
Kevin Avatar answered Nov 28 '22 01:11

Kevin