Definition and Usage
- PHP Version
- 4+
The join() function joins array elements into a string using a custom delimiter.
This function returns a single string by joining each element of a given array with a specified delimiter.
Basic Example
$colors = ['red', 'green', 'blue'];
$comma_separated = join(', ', $colors); // Join with a ', ' delimiter
echo $comma_separated; // Output: 'red, green, blue'
Syntax
join(string $separator, array $array): string
Parameters
$separator |
Optional. The delimiter used to join the elements of the array.
Defaults to an empty string ( ''). |
|---|---|
$array |
The array to join into a string. |
Return Values
The join() returns a string created by joining the elements of an array in order, separated by a specified delimiter.
Practical Examples
The following examples demonstrate how the join() function behaves in various scenarios.
Basic Usage
$fruits = ['apple', 'banana', 'cherry'];
$fruits_string = join(', ', $fruits);
echo $fruits_string; // Output: 'apple, banana, cherry'
In this example, the elements of the $fruits array are joined into a single string using a comma and a space (', ') as the delimiter.
Generating an HTML List
$items = ['Item 1', 'Item 2', 'Item 3'];
$html_list = '<ul><li>' . join('</li><li>', $items) . '</li></ul>';
echo "HTML List:\n" . $html_list;
- Item 1
- Item 2
- Item 3
Objects Can Be Included in the Array Passed to the join() Function
class StringArray {
protected $title;
public function __construct($title)
{
$this->title = $title;
}
public function __toString()
{
return $this->title;
}
}
$array = [
new StringArray('Spring'),
new StringArray('Summer'),
new StringArray('Autumn'),
new StringArray('Winter')
];
echo join('; ', $array); // Output: 'Spring; Summer; Autumn; Winter'
Caution
Be aware that the array passed to join() may contain boolean values.
In such cases, the function can produce unexpected results due to type conversion.
$booleans_array = [true, true, false, false, true];
$result = join('', $booleans_array);
var_dump($result); // Output: string(3) "111"
// true is converted to "1", and false becomes an empty string.