search

Home  >  Q&A  >  body text

What is the difference between collection and array in laravel?

What is the difference between collections and arrays in laravel?

高洛峰高洛峰2829 days ago584

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 16:48:40

    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;

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 16:48:40

    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

    reply
    0
  • Cancelreply