jericopulvera's avatar

How to replace the array key of a collection

Collection {#233 ▼
        #items: array:3 [▼
              0 => Post {#297 ▶}
              11 => Post {#308 ▶}
              10 => Post {#307 ▶}
        ]
}  

How do I replace the array key to

Collection {#233 ▼
        #items: array:3 [▼
              0 => Post {#297 ▶}
              1 => Post {#308 ▶}
              2 => Post {#307 ▶}
        ]
}  
0 likes
3 replies
jericopulvera's avatar

@tomi what's the difference between unique() and values()? they seem to do the same.

tomopongrac's avatar

Unique removes duplicated items ... check the example in documentation

$collection = collect([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], // <-- this is removed because duplicated brand
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], // <-- this is removed because duplicated brand
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], // <-- this is removed because duplicated brand
]);

$unique = $collection->unique('brand');

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
*/

Please or to participate in this conversation.