preface


Collections are instantiated as Illuminate\Support\Collection, and Laravel’s kernel uses them for most of its parameter passing, but that doesn’t mean they’re good. Laravel is a fast and elegant development framework for a reason, not because of its routing, DB, listener, etc. When you need to deal with arrays, you may need it to help you solve real problems quickly.

Create a collection

$collection = collect([1, 2, 3]); Copy the code

Obviously, this is a very simple operation, and if you want to say “it’s complicated”, it’s more similar to the way the earlier PHP5.x versions were declared.

$collection = array (1, 2, 3);

Laravel doesn’t do anything complicated with Collection either. I will see the next chapter “Laravel Source Code Parsing Collection”. Thank you

Back to the prototype

If you want to convert collections to data, it’s also very simple to use

collect([1, 2, 3])->all(); -- -- -- -- -- - > [1, 2, 3]Copy the code

For performance reasons, you can use Laravel collections, which will do 90 percent of your array operations for you.

For example, we need to split an array by a horizontal line into two or more arrays. Use collections to do this

$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray(); // [1, 2, 3, 4], [5, 6, 7]]Copy the code

And some methods are designed according to the way SQL statements are queried. Let’s take a look at what they are.

Methods list

Here is a list of some common collection operations, please refer to the official details and all.

Thank you

Thank you for reading this and I hope this article helped you. Thank you. Why don’t you get back to practice?

To learn more, please visit:

Tencent T3-T4 standard boutique PHP architect tutorial directory directory, as long as you finish the guarantee salary rise a step (continue to update)


I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx, etc.