What is the difference between collection and array in laravel?
高洛峰
高洛峰 2017-05-16 16:46:40
0
2
457

What is the difference between collections and arrays in laravel?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
曾经蜡笔没有小新

Array in Laravel, source code locationIlluminateSupportArr.php;

Collections in Laravel, source code locationIlluminateSupportCollection.php;

A collection is a re-encapsulation of an array and is presented in the form of an object; it provides many method functions (most of these methods use callback functions internally), which is much more flexible than array-based operations;

Essentially, it’s the difference between operating elements in object-oriented form and operating elements in array form; if you operate with objects, as vika_倾慕 said, you can chain operations; if you operate with arrays, many intermediate temporary variables or statements and codes will be generated Seems verbose;

洪涛

What makes collections more powerful than arrays is that they use various map/reduce intuitive operations. For example, we remove all inactive user models and collect the names of the remaining users:

$users = App\User::where('active', 1)->get();

$names = $users->reject(function ($user) {
    return $user->active === false;
})
->map(function ($user) {
    return $user->name;
});

If you think it’s okay, remember to adopt it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!