The new Arr::join() method in Laravel 9.x — Amit Merchant — A blog on PHP, JavaScript, and more

0
14

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 IlluminateSupportArr and IlluminateSupportCollection 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 IlluminateSupportArr;

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

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

Pretty simple but a very useful one!

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here