0
0
PHPprogramming~5 mins

Implode and join in PHP

Choose your learning style9 modes available
Introduction
Implode and join combine array elements into a single string with a separator. This helps turn lists into readable text.
You want to display a list of names separated by commas.
You need to create a sentence from words stored in an array.
You want to save array data as a single string in a file or database.
You want to build a URL query string from parameters stored in an array.
Syntax
PHP
string implode(string $separator, array $array)
string join(string $separator, array $array)
implode and join do the same thing; join is an alias of implode.
The separator is placed between array elements in the resulting string.
Examples
Joins array elements with a comma and space.
PHP
$array = ['apple', 'banana', 'cherry'];
$result = implode(', ', $array);
echo $result;
Joins array elements with a dash surrounded by spaces.
PHP
$array = ['red', 'green', 'blue'];
$result = join(' - ', $array);
echo $result;
Joins array elements with no separator, just concatenates.
PHP
$array = ['one', 'two', 'three'];
$result = implode('', $array);
echo $result;
Sample Program
This program joins the fruits array into a string separated by commas and prints it.
PHP
<?php
$fruits = ['apple', 'banana', 'cherry'];
$sentence = implode(', ', $fruits);
echo "Fruits: $sentence.";
OutputSuccess
Important Notes
If the array is empty, implode returns an empty string.
You can use any string as a separator, including spaces, commas, or special characters.
implode works only on arrays, not on other data types.
Summary
implode and join combine array elements into one string.
You choose the separator to put between elements.
They are useful to make readable lists or save arrays as strings.