Search

Considerations of Using the array_sort Laravel Helper Function

November 20, 2016 —John Koster

The array_sort function (discussed in the Laravel Array Helper Function: array_sort article) internally creates a new instance of the \Illuminate\Support\Collection class with the given $array and then calls the collection's sortBy(callable $callback = null) method with the given $callback. It then converts the sorted collection into an array by calling the collection's all() method. In short, this function creates a new object every time it is invoked.

Because of this function's internal behavior, code should never be written like the following:

1<?php
2 
3// Create a new collection, using the 'Collect' helper.
4$collection = collect(['second', 'first', 'third']);
5$sorted = array_sort($collection->all());

Instead, it is preferable to just use the collection's sortBy method directly:

1<?php
2 
3$collection = collect(['second', 'first', 'third']);
4$sorted = $collection->sortBy();

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.