Similar to this question but for PHP. I want to concatenate an array of strings but ignore blanks.
For instance, suppose I want to build a full_name
attribute in Laravel using $this->title
, $this->first_name
, and $this->last_name
, each separated by single space. The simplest thought I had was to put them all into an array and pass it into implode()
as in below:
implode(' ', [$this->title, $this->first_name, $this->last_name]);
However I don't know whether those values are actually going to be set or not. And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements. Is there a built-in function or at least a simpler/shorter way to do the below?
public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
$result = '';
foreach($arrayOfStrings as $piece)
$result .= isset($piece) ? $piece . $glue : '';
return $result;
}