Join my Laravel for REST API's course on Udemy 👀

Join array items by a string character in PHP

May 13, 2022  ‐ 1 min read

Coming from Python I got quited used to the .join() method that allows you to join array items together as a string separated by a specified character.

Although not called join in PHP, PHP does provide an equivalent function called implode(). This being the opposite of the explode() function which splits a string on a specified character into an array of substrings.

The implode() function requires a string separator and the array to join as a string.

<?php

$reserved = ['app', 'home', 'about'];

echo implode(',', $reserved);
// => "app,home,about"

What you use as a separator is up to you obviously, see here an example with dashes instead of comma's.

<?php

$reserved = ['app', 'home', 'about'];

echo implode('-', $reserved);
// => "app-home-about"

To join the array items together as a single word string you could use an empty string as the separator:

<?php

$reserved = ['app', 'home', 'about'];

echo implode('', $reserved);
// => "apphomeabout"

However, in this case the string separator is optional, and you can achieve the same by not providing a separator string at all.

<?php

$reserved = ['app', 'home', 'about'];

echo implode($reserved);
// => "apphomeabout"