Last Updated On By Anmol Lohana
The implode() function is a built-in function of PHP, and it works the same as the join() function works. It is used to join the elements of an array and convert them into a string. PHP implode() function accepts two parameters as arguments; one is required, and one is optional. The first parameter is “separator,” which gives a separator between the values in the form of a string. The elements of an array join to form a string, and each value will be separated by a separator given in parameter. This parameter is an optional parameter by default; it takes an empty string. The second parameter is “array,” and it is a required parameter. It is the one whose value is to be changed. This PHP implode() function will return a string that is formed with the elements of an array.
Table of Contents
implode(separator,array)
In this example, we will perform array to string conversion using PHP implode() function. We will create an array of fruits and convert it into a string. A comma will separate each item.
<?php
$ar = ['apple', 'orange', 'pear', 'grape'];
echo "Fruits Array";
echo "<br>";
echo implode(', ', $ar);
?>
We can also convert an array of the array means a nested array, into a string by using the PHP implode() function. The below example will show that how to do it.
<?php
$movies = [
'comedy' => ['In the Loop', '21 Jump Street', 'Elf ', 'This Is the End'],
'war' => ['Dunkirk', 'Hacksaw Ridge', 'Inglourious Basterds', 'Defiance'],
'action' => ['La La Land', 'The Notebook', 'About Time', 'Twilight'],
'sci fi' => ['Interstellar', 'Annihilation', 'Gravity', 'Inception'],
];
foreach ($movies as $list){
echo "<br>";
print_r(implode(", ", $list));
}
?>
In conclusion, we discussed the PHP implode() function converting an array or array of arrays into a string. It was accepting two parameters one was required the “array,” and one was optional the “separator.” Two coding examples are also given. That will make your concept clearer.