Laravel’s Collection class is a huge advantage of the framework. But why? Why is it so painful to use the native array functionality of PHP? Let’s take a look at some comparison of how PHP and JS handle arrays and discover the big difference.

Filtering Arrays

When we need to work with datasets, usually we may filter them. We can pass a closure and if the truth test passes, the filter keeps the value of the array, otherwise, it drops the item.

$filtered = array_filter([1, 2, 3, 4], function ($item) {
    return $item > 2;
});
let filtered = [1, 2, 3, 4].filter(item => item > 2);

Mapping Arrays

Mapping through arrays is also one of the most popular actions. It’s a nice way to transform the current dataset and make a new array of it.

$mapped = array_map(function ($item) {
    return $item * 2;
}, [1, 2, 3, 4]);
let mapped = [1, 2, 3, 4].map(item => item * 2);

Pushing Arrays

With pushing arrays, we can append elements at the and of our dataset.

$items = [1, 2, 3, 4];

array_push($items, 5);

// OR

$items[] = 5;
let items = [1, 2, 3, 4];

items.push(5);

Unshifting Arrays

Unshifting arrays is the totally opposite of pushing. It prepends the given item at the beginning of the array.

$items = [2, 3, 4];

array_unshift($items, 1);
let items = [2, 3, 4];

items.unshift(1);

Why is it interesting at all?

First of all, we just covered a very little part of the functionality that PHP and JS offer to handle arrays. But we need to notice something. PHP handles arrays via functions but JS uses the object-oriented way.

Imagine a situation, where you need to nest some array functions in PHP. It can be a huge mess and indentation nightmare. But approaching the same result with JS much more elegant, since we can chain methods instead of nesting them.

array_filter(array_map(function ($item) {
    return $item * 2;
}, [1, 2, 3, 4]), function ($item) {
    return $item > 4;
});
[1, 2, 3, 4].map(item => item * 2)
            .filter(item => item > 4);
Also, we can notice, that PHP is not strict with the parameters. It happens, that once, the closure is the first parameter, and sometimes it’s the second.

We can see, the JS way is much cleaner than the native PHP functionality. The difference is coming on the surface only when we try to nest or chain functions and methods.

This is one of the problems that Laravel’s collection solves for us. We can easily use the array mapping, filtering, pushing functionality with one single chain. It becomes cleaner with fewer indentations.