It is basically a API wrapper for PHP array functions. But it has much more features which benefit array processing.
1. Avoid braces hell
think this case with at 5 braces:
shuffle(shuffle(arsort(array_unique(array_merge($array1,$array2)))));
This is hell, if the array with more than 10 braces, you might lose track of the brace in the end. However, if you use Collection, it can be replaced with:
collect($array1)
->merge($array2)
->unique()
->sort()
->shuffle()
->shuffle()
This is more readable, object-oriented and flow-thinking.
2. Unify the use of API
It is PHP original API issue that you never know where the array should in parameter. they just not consistent. for example:
array_walk ( $array , $callback );
array_map ( $callback , $array);
array_merge ( $array1 ,$array2 );// return a new array
array_push ($array1 ,$value); // not return a new array
Laravel Collect just provide consistent API make my life easier.
collect($array)
->each($callback)
->map($callback)
->merge($array2)
->push($value)
3.Collection API process key-value array better
Laravel focus on processing data from a database. So many cases are with key-value array situation, rather than an indexed array. So Laravel collection has many extended methods against the original PHP functions, which process with key of the array . For example:
$array=[
["id"=>1,"name"=>"Apple"],
["id"=>2,"name"=>"Banana"],
["id"=>1,"name"=>"Apple"],
["id"=>2,"name"=>"Banana"],
];
$result= collect($array)->unique("id");
The result will be:
Array
(
[0] => Array
(
[id] => 1
[name] => Apple
)
[1] => Array
(
[id] => 2
[name] => Banana
)
)
4. Dealing with multi layer array
Most of PHP original array API only deal with the top layer of an array. if you want to process the deep layer of an array, the code might become much more complex. But many APIs of Laravel collection allow you to access the deep layer of the array.
For example:
$array=[
["id"=>1,"product"=>['name'=>"Apple"]],
["id"=>2,"product"=>['name'=>"Watermelon"]],
["id"=>3,"product"=>['name'=>"Banana"]],
];
$result= collect($array)->sortBy("product.name");
The result will be:
Array
(
[0] => Array
(
[id] => 1
[product] => Array
(
[name] => Apple
)
)
[2] => Array
(
[id] => 3
[product] => Array
(
[name] => Banana
)
)
[1] => Array
(
[id] => 2
[product] => Array
(
[name] => Watermelon
)
)
)
5. More missing array helpers from the original PHP
Besides above, Laravel collection increases many very useful array APIs in each new versions. Many useful Helpers were designed to process the Key-Value type of the array and so useful for developing the application. like: keyBy()
, where()
, isEmpty()
, isNotEmpty()
and so on.
Furthermore, Collection is macroable which means you can extend Collection API, make Collection much more suitable for your project.
All in all, The Laravel collection is powerful array processing Helper for my development.