Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The new Arr::join() method in Laravel 9.x

May 7, 2022 ·

A while back, I have written an article on how to convert arrays to human-readable lists in JavaScript. It’s a built-in feature using the Intl.ListFormat object that lets you do that.

Essentially, this will let you deflate items of an array in a human-readable form.

So, if we have the following array…

const books = [
    'Harry Potter',
    'Bhagavad Gita',
    'The Alchemist',
    'Birthday Girl'

…it can be deflated in this format.

“Harry Potter, Bhagavad Gita, The Alchemist, and Birthday Girl”

You can read more about this feature of JavaScript in this article but Laravel has got a similar feature recently that let you do just that starting from Laravel 9.x.

The Arr:join() method

This PR by Daniel Eckermann adds a new method join() in Illuminate\Support\Arr and Illuminate\Support\Collection that lets you deflate any array into whatever format you want.

Here’s what the definition of the join() method looks like.

public static function join($array, $glue, $finalGlue = '')

As you can tell, the method accepts three parameters of which two are mandatory and the last one is optional.

  • The first parameter is an array that needs to be deflated.
  • The second parameter is the glue using which the array items will get stitched together.
  • When you pass in the third parameter, it will use that final glue to join the last two items instead.

So, if we have the following array…

$books = [
    'Harry Potter',
    'Bhagavad Gita',
    'The Alchemist',
    'Birthday Girl'

And if we want to deflate it as a human-readable list, here’s how we can do it.

use Illuminate\Support\Arr;

$bookList = Arr::join($books, ', ', ' and ');

// Harry Potter, Bhagavad Gita, The Alchemist and Birthday Girl

Pretty simple but a very useful one!

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!