I need to concatenate an indeterminate number of strings, and I would like a space in between two adjoining strings. Like so a b c d e f.
Also I do not want any leading or trailing spaces, what is the best way to do this in PHP?
I need to concatenate an indeterminate number of strings, and I would like a space in between two adjoining strings. Like so a b c d e f.
Also I do not want any leading or trailing spaces, what is the best way to do this in PHP?
I just want to add to deviousdodo's answer that if there is a case that there are empty strings in the array and you don't want these to appear in the concatenated string, such as "a,b,,d,,f" then it will better to use the following:
$str = implode(',', array_filter(array('a', 'b', '', 'd', '', 'f')));
considering that you have all these strings collected into an array, a way to do it could be trough a foreach sentence like:
$res = "";
foreach($strings as $str) {
$res.= $str." ";
}
if(strlen($res > 0))
$res = substr($res,-1);
in this way you can have control over the process for future changes.
implode().foreach) assumes the strings are in an array. Usage of implode would also assume the strings are in an array. I don't see the freedom here, I only see a bunch of unnecessary lines which decrease readability.