Code Example

Let’s begin by setting up the world. Suppose we’ve queried some API and we’ve gotten some results back as an array:

// Results from an API request

$data = [ ['first_name' => 'John', 'last_name' => 'Doe', 'age' => 'twenties'],

['first_name' => 'Fred', 'last_name' => 'Ali', 'age' => 'thirties'],

['first_name' => 'Alex', 'last_name' => 'Cho', 'age' => 'thirties'], ];

As we can see, the array contains first names, last names and age ranges. Now, let’s suppose we need to extract the records with an age in the thirties, and then sort them by last name . Finally, we want the results as a single string , with each one on a new line .

On paper, that’s a very simple requirement, but take a look at the PHP code needed to achieve that result:

// Sort results by last name

usort($data, function($item1, $item2) {

return $item1['last_name'] <=> $item2['last_name'];

}); // Group results by age range

$new_data = []; foreach($data as $key => $item) {

$new_data[$item['age']][$key] = $item;

} ksort($new_data, SORT_NUMERIC); // Retrieve the full names of people in their thirties

$results = array_map(function($item) {

return $item['first_name'].' '.$item['last_name'];

}, $new_data['thirties']); // Convert array to a string with new line separators

$final = implode($results, "

");

It requires twenty lines of code, and it’s ugly as hell. Take out the comments for guidance / breaking it up, and it’s even more indecipherable. Plus, we have to use temporary variables and PHP’s unfriendly sort methods.

Now, let’s see how much simpler it can be by using the collection class:

collect($data) -> where('age', 'thirties')

-> sortBy('last_name')

-> map(function($item) {

return $item['first_name'].' '.$item['last_name'];

})

-> implode("

")

Wow! We’ve gone from 20 lines to 6. The code is now fluent, and we don’t need helper comments as the method names tell us exactly what’s happening.