Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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

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 (including 8.1, 8.2, and 8.3), 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-digest 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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?