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!
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.