Framework: Collection::push() and pull() with given key

Created on 24 Aug 2015  路  8Comments  路  Source: laravel/framework

Hi,

I've run into a situation where I needed an item with a specific key on the beginning of the colletion. In this case I could just transform the collection into an array and use + operator, but it would be great if push() and pull() had a second optional argument with the key name.

Most helpful comment

Thanks to ArrayAccess you can push new keys to your collection by doing:

$collection['keyName'] = 'value';

All 8 comments

If you want to prepend a collection with keyed item you can use merge:

$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection = collect(['price' => 123])->merge($collection);

$collection->all();
// [
//  "price" => 123,
//  "product_id" => "prod-100",
//  "name" => "Desk",
// ]

I don't think that complicating push and pull is a good idea. Possibly introducing a new method putAt might be a solution but merge for keyed elements and prepend for non-keyed are OK.

Sure, but merge() uses array_merge(), which messes up the numeric keys (the same problem with array_unshift).

@GrahamCampbell: maybe you should consider closing issues with a comment? I won't guess if it's closed as "we don't care", "it's good as is" or "make a PR and we will think".

@GrahamCampbell: hello?

This doesn't need changing.

@GrahamCampbell: currently it's consistent with PHP's poor implementation. But you have the chance to make your Collection something better, why don't go this way? Although if the consistency is a must, then ok.

Thanks to ArrayAccess you can push new keys to your collection by doing:

$collection['keyName'] = 'value';

I think push() pull() should be consistent with their names :3 normally in data structures arent we using pull to pull the last item and push to append and item to the next index? shouldnt they work that way when we didnt specify an index?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iivanov2 picture iivanov2  路  3Comments

progmars picture progmars  路  3Comments

SachinAgarwal1337 picture SachinAgarwal1337  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments