Join non-empty strings in PHP
Sometimes you have to join strings but keep them divided by a character (space, comma…). For example you want to output the full name of a customer, and to save time you do:
$str = $customer->lastname . ' ' . $customer->firstname . ' ' . $customer->fathername;
But if any of values is absent then you’ll end up with 2 spaces in a row (which is ok as browser will show only one if these are not non-breaking spaces). But how about dividing by commas? Noboy wants 2 commas in a row. Most probably you’ll through the following steps:
- create an array
- populate it with all non-empty values
- join them
Here’s the same sollution but in one line:
$str = join(' ', array_filter(array($customer->lastname, $customer->firstname, $customer->fathername)));