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(); ?>
2
  • 3
    echo implode(', ', array($variable1, $variable2, ...)); Commented Apr 29, 2015 at 7:13
  • 3
    @billyonecan : Won't work Commented Apr 29, 2015 at 7:15

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.