Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way To Concatenate Strings In PHP With Spaces In Between

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?

like image 987
freshest Avatar asked Nov 09 '11 16:11

freshest


3 Answers

You mean $str = implode(' ', array('a', 'b', 'c', 'd', 'e', 'f'));?

like image 120
deviousdodo Avatar answered Oct 20 '22 07:10

deviousdodo


Simple way is:

$string="hello" . " " . "world";
like image 6
user2033108 Avatar answered Oct 20 '22 08:10

user2033108


function concatenate()
{
    $return = array();
    $numargs = func_num_args();
    $arg_list = func_get_args();
    for($i = 0; $i < $numargs; $i++)
    {
        if(empty($arg_list[$i])) continue;
        $return[] = trim($arg_list[$i]);
    }
    return implode(' ', $return);
}

echo concatenate("Mark ", " as ", " correct");
like image 4
Dejan Marjanović Avatar answered Oct 20 '22 08:10

Dejan Marjanović