Search code examples
phparraysstringimplode

trim before implode in php to get trimmed strings


$array = array(' lastname ', ' email ', ' phone ');
$comma_separated = implode(" ", $array);

echo $comma_separated; // lastname  email  phone

I have the above code to combine or join string in PHP problem is if the element in array has extra in joined string it has extra space.

Expected Result:Only one space between words in echo

How to first trim each element in array before implode


Solution

  • use Following Code :

    $array =  array(' lastname ', ' ',' email ', ' phone ');
    
    $trimedarray=array_map("trim",$array);
    
    $modifiedarray=array_values(array_filter($trimedarray)); 
    
    $comma_separated = implode(" ", $modifiedarray);
    
    echo $comma_separated;