PHP implode - Array to string
In this tutorial, we look at the PHP implode function. We will learn how it returns a string from the elements of an array.Table of Contents - PHP implode
- What is PHP implode?
- What is the difference between explode and implode in PHP?
- Syntax for PHP implode function
- PHP implode function examples
- Closing thoughts
- Other Related Concepts
What is implode?
The implode() function returns a new string which is the result of joining the string elements in the array with the separator.The order of the elements in the resultant string is the same as the order they appear in the array. And if the array is empty, then the implode() function will also return an empty string.
Note: The join() function is used interchangeably with the implode() function. This is because they both achieve the same result.
What is the difference between the implode and explode functions in PHP?
The implode function returns the joined elements of an array as a string. However, the explode function splits the string into a specified number of pieces. In other words, it breaks a string into an array. You can read more about the explode function in PHP here.Syntax of the PHP implode function
This is the syntax of the function:implode(separator, array)
The function has two parameters:
- The separator is the character that separates two strings. If $separator is used, it defaults into an empty string.
- The array whose value is to be joined to form the resultant string.
Note: The separator parameter is optional, but recommended.
PHP implode function examples
Let’s look at some examples of the implode function’s usage.Joining strings using the implode function
In this section, we look at an example of joining the string elements of an array into a new string.Input:
?php
$column_heading = ['first_name', 'age', 'phone number', 'address'];
$sample_header = implode('; ', $column_heading);
echo $sample_header;
Output:
first_name; age; phone number; address
Here is another example of joining the array elements with various characters.
Input:
?php
$trial = array('This','is','PHP','simplified');
echo implode("|",$trial)."
";
echo implode("*",$trial)."
";
echo implode("+",$trial)."
";
echo implode("_",$trial);
?>
Output:
This|is|PHP|simplified
This*is*PHP*simplified
This+is+PHP+simplified
This_is_PHP_simplified
Joining elements of an associative array with the implode function
If we pass an associative array to the implode function, then only the array’s values will be joined. The keys of the array will be ignored in this instance.Input:
?php
$details = [
'company_name' => 'Frank',
'domain' => 'Smith'
'Male'
];
echo implode(',', $details);
Output:
Frank,Smith,Male
In this example, the values of the array $details were taken into account, while the keys were disregarded.