New undot() and reverse() methods in Laravel 8.x

Amit Merchant · December 4, 2021 ·

Some may argue that Laravel is a framework that is bloated with methods and stuff to do everything under the sun. But in my opinion, that’s one of those things that make Laravel, “Laravel” because the more options you have out of the box, the better your life gets!

The recent release of Laravel comes with two such small “life-improvement” methods which aren’t fancy enough but you may have always wanted them.

The reverse() method

There’s now a helper method called reverse() in Illuminate\Support\Str and Illuminate\Support\Stringable using which it’s now convenient to reverse strings.

use Illuminate\Support\Str;

echo Str::reverse('raBooF');
// FooBar

echo Str::of('FooBar')->reverse();
// raBooF

The good thing about this method is it also works with multibyte strings flawlessly.

echo Str::reverse('őtüzsineT');

// Teniszütő

The undot() method

And next, the framework has got the counterpart of the Arr::dot() method called undot().

Where the Illuminate\Support\Arr::dot()method flattens a multi-dimensional array into a single level array that uses “dot” notation to indicate depth, the Arr::undot() method does exactly opposite og it.

So, for instance, if we have the following flatten array with the dot notation…

$productInfo = [
    'products.desk.price' => 100
];

…we can unflatten or make it multi-dimensional using the undot() method like so.

use Illuminate\Support\Arr;

$unflattenedProductInfo = Arr::undot($productInfo);

/* 
[
    'products' => [
        'desk' => [
            'price' => 100
        ]
    ]
];
*/
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!

Comments?