How to Convert an Array to a String in PHP


An array is a useful tool for storing a series of items, such as sentences in a paragraph or paragraphs in a document. However, you may want to combine the individual elements of an array into a single string -- to parse and output to a file, for example. There are two different ways to convert an array to a string. The first method uses simple string concatenation; the second method uses the PHP function implode.

  • Create an array containing the data you want to convert to a string. For example, type:


    $array = array("This is the first sentence.", "This is the second sentence.", "This is the third sentence.");

  • Initialize a variable to be a blank string. Loop through each element in the array and add it to the string, followed by a blank space. Remove the trailing blank space after the last array element is added with the trim function. Output the result. For example, type:

    $string1 = "";

    foreach ($array as $string) $string1 .= $string . " ";

    $string1 = trim($string1);

    echo $string1;

  • Call the PHP implode function with a blank space as the first parameter to combine each of the array elements automatically into a single string separated by the blank space. Output the result. For example, type:

    $string2 = implode(" ", $array);

    echo $string2;


Related Searches


Promoted By Zergnet


Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!