Home > Back-end >  check if variable empty in implode and dont show separator
check if variable empty in implode and dont show separator

Time:06-08

It is possible to check if the variable is empty - replace or change the separator

<?php echo implode(', ', [$var1, $var2, $var3]); ?>

now if $var2 is empty - I get output like 'value1, ,value3'

I can't cover all output in if-statement, because I must get output even if one of the variables is empty - I just need to hide the separator in this case

CodePudding user response:

Use array_filter() to remove empty values.

echo implode(', ', array_filter([$var1, $var2, $var3]));

DEMO

Note that if this is an array of numbers, the number 0 will be considered falsey. In that case, you should provide a callback function that explicitly checks for an empty string.

  • Related