PHP Display a comma after each variable if the variable is not empty

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

<?php echo $City; ?>, <?php echo $Province(); ?>, <?php echo $PostalCode(); ?>, <?php echo $Country(); ?>
+4
source share
1 answer

Another way is to place them inside an array in conjunction with array_filterto clear empty lines and blow them up:

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

Sidenote: If you also want to handle empty spaces, you can display trimon elements and then filter:

$test = array_filter(array_map('trim', array('1', ' ', 'test')));
                                              //   ^ single space
+10
source

All Articles