DEV Community

Jacob Landry
Jacob Landry

Posted on

Illuminate Collections vs. PHP Arrays

I recently published a deep-dive look at the difference between Laravel Collections and standard PHP functionality on Hackernoon.

Have a look!
https://hackernoon.com/illuminate-collections-vs-php-arrays

Top comments (2)

Collapse
 
xwero profile image
david duymelinck

The biggest difference between Laravel collections and php is that you can add your own methods. I think that is more important than a fluent api.

The code of the examples doesn't show how a collection is more readable. Even the all together example looks very readable. The only thing I would change are the variable names to make it clear what the flow is.

$b = array_filter($a, function($row) {
    return substr($row, 0, 1) === "a";
});

$c = array_search(function($row) {
    return substr($row, 0, 1) === "a";
}, $b);

$d = array_map(function($row) {
    return "test";
}, $c);

sort($d);

foreach($d as $item) {
    $doSomething = true;
}

$sum = array_reduce($d, function($carry, $row) {
    return $carry + strlen($row);
});
Enter fullscreen mode Exit fullscreen mode

Naming things, even just with a letter, is very powerful. In this case to establish a flow. When there is a letter out of place you will notice it.

If a collection/array requires a lot of actions, why not check if the actions can be reduced before it gets to that part of your code, for example with a data object.

In short I think most of the time there is a better solution than relying on a Collection instance.

Collapse
 
suckup_de profile image
Lars Moelleken

I builded many collection classes and often the simplest way is just a array with phpdocs. 😜 chatgpt.com/share/671d8a50-aa5c-80...