How to Use the PHP implode() Function

09/06/2021

Contents

In this article, you will learn how to use the PHP implode() function.

PHP implode() Function

The implode() function in PHP is used to join elements of an array into a single string.

Syntax:
string implode ( string $glue , array $pieces )
Parameters:

The function takes two parameters:

  • $glue: The string that will be used to separate the array elements.
  • $pieces: This is the array that you want to join into a single string.
Example:
<?php
  $array = array('apple', 'banana', 'cherry');
  $string = implode(", ", $array);

  echo $string;
  // Output: apple, banana, cherry
?>

In this example, the elements of the $array are joined into a single string, separated by the “, ” string, and the result is assigned to the $string variable.

The implode() function can be useful in many different situations where you need to convert an array into a string. For example, you may use this function to convert an array of values into a comma-separated string that can be stored in a database, or to convert an array of values into a list of HTML options for a drop-down menu.

It’s also worth mentioning that the implode() function is the opposite of the explode() function in PHP. The explode() function takes a string and splits it into an array based on a specified separator.

Here is an example of how you can use the implode() and explode() functions together:

<?php
  $string = "apple, banana, cherry";
  $array = explode(", ", $string);

  print_r($array);
  // Output: Array ( [0] => apple [1] => banana [2] => cherry )

  $glue = ', ';
  $new_string = implode($glue, $array);

  echo $new_string;
  // Output: apple, banana, cherry
?>

In this example, the $string is first split into an array using the explode() function, and the result is assigned to the $array variable. Then, the $array is joined into a single string using the implode() function, and the result is assigned to the $new_string variable.