DEV Community

Youn
Youn

Posted on

PHP join() Function – Convert an Array to a String

😄 This post is based on the content from coding.courses.

Definition and Usage

(PHP Version | 4+)

The join() function joins array elements into a string using a custom delimiter.
The join() function is an alias of the implode() function. It works identically to the implode() function.
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'
Enter fullscreen mode Exit fullscreen mode

Syntax

join(string $separator, array $array): string
Enter fullscreen mode Exit fullscreen mode

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

# Basic Usage

$fruits = ['apple', 'banana', 'cherry'];
$fruits_string = join(', ', $fruits);

echo $fruits_string; // Output: 'apple, banana, cherry'
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

This example joins the array elements into an HTML unordered list by wrapping each item with <li> tags and enclosing the whole result in <ul>.

# 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'
Enter fullscreen mode Exit fullscreen mode

References

PHP join() Function – Convert an Array to a String - codingCourses

The join() function joins array elements into a single string. It is an alias of the implode() function and works identically to it.

favicon coding.courses

Top comments (0)