PHP "Array to String" (Examples of How to Use the implode Function)

PHP Command Tutorial: How to use implode

In PHP, the implode() method joins array elements and outputs them as a single string. This is useful when you need to create one string out of a set of array values.

The function can be invoked in two ways (with or without the glue string):

  1. implode( string $glue , array $pieces ) – The glue is used to combine the array pieces.
  2. implode( array $pieces ) – No glue is used, so the pieces will be concatenated together.

We’ll go through examples of both, as well as how to go from a string to an array, below.

Example: Using implode to Go From an Array to a String

To output an array as a string, where each array value is separated by a comma and a space, you would do the following:

Without the previous glue string comma, this would be the result:

It’s Worth Knowing About print_r, var_dump, and json_encode

Other functions that prove useful for looking at the values of arrays are print_r and var_dump. These two functions can be extremely useful when you are debugging a program and want to see the output of an array (or any variable).

Also, json_encode will take your array data and output it as a string in JSON-encoded format.

Bonus: How To Go From a String to an Array (The Reverse of Implode)

The reverse action — going from a string to an array — can be done easily with explode, or by using the preg_split function, which takes a regular expression.

Using explode

You guessed it: explode is the opposite of implode and uses a delimiter to decide where to break up a string. It is usually the simplest way to break up a string into an array.

The above would result in the output below:

Using preg_split

If your delimiter is REALLY complicated, it might make sense to use a regular expression to define it. If this is the case, you can use preg_split.

This would also output the following:

Okay, that is enough PHP string manipulation for now. Just don’t be afraid to implode!

PJ Fancher

Questions or Comments? Ask PJ!

Ask a question and PJ will respond to you. We strive to provide the best advice on the net and we are here to help you in any way we can.

  • Michael Misheck

    hi, am inserting data in a mysql table in form of an array, I have a set of check boxes such that some are to be selected and some not depending with the availability of the items. I want the selected box to be submitted as on and those not checked to be submitted as off. This data has to tally with the IDs available. my problem is that when I insert the unchecked boxes are inserted last in stead of tallying with the id. I tried to use explode() function but it didn’t work for me. any help please?