PHP Array to String Conversion by Implode function

In this chapter, we will explain how to use implode() function of PHP to convert an array to a string. Note that the Join() is an alias to implode() function.

See implode example
  • In certain scenarios, you might need to convert array values to string.
  • You can convert an array to string by using implode() function of PHP.
  • The implode() function places the separator (+ or some other special symbol) between each value of array element.
  • The implode() basically joins array elements with a string.
An implode example with + separator

How to use implode function for array to string conversion?

This is how you may use the implode function of PHP for converting an array to string:

string implode ($separator,$array_name)

Note: If you don’t place a separator then PHP will not generate any error message.

An example of array to string by implode with comma

In the following example, a single dimensional array is created with three elements.  After that, the implode function is used with that array for converting the array into the string. The comma is used as the separator. The end result is displayed by using the echo statement, have a look:

Experience this example online

You saw the converted string is displayed with the array elements joined with a comma.

Using the + characters as separator example

Now, using the same array of three elements as in above example, however, this time I used the + character rather than a comma to join the array elements after conversion by implode function. See the code and output:

Experience this example online

You can see, the array elements are joined with the + character.

An example with two-dimensional array

In this example, an array of three elements is created. The array contains fruit names. After that, the implode PHP function is used for converting this array to string. Finally, the print_r function is used for displaying it:

Experience this example online




You should also read: PHP arrays