5

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(); ?>
user3351236
  • 2,488
  • 10
  • 29
  • 52

1 Answers1

13

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
Kevin
  • 41,694
  • 12
  • 53
  • 70