Framework: [Proposal] Reset array_keys when filtering a Collection

Created on 17 May 2013  路  4Comments  路  Source: laravel/framework

The current implementation is the following

    /**
     * Run a filter over each of the items.
     *
     * @param  Closure  $callback
     * @return \Illuminate\Support\Collection
     */
    public function filter(Closure $callback)
    {
        return new static(array_filter($this->items, $callback));
    }

array_map has the side effect that it will keep the array keys as they were originally

As a result, when json-i-fying the filtered result, the result will not be a simple array, but an object with key=>value pairs.

For example:

{"4": {"name": "Koen"}, "7": {"name": "Taylor"}}

VS

[{"name": "Koen"}, {"name": "Taylor"}]

I suggest we change the filter method into this:

    /**
     * Run a filter over each of the items.
     *
     * @param  Closure  $callback
     * @return \Illuminate\Support\Collection
     */
    public function filter(Closure $callback)
    {
        return new static(array_values(array_filter($this->items, $callback)));
    }

Which will clean up the keys, and turn everything back to normal.

Most helpful comment

I would just run values on the Collection. Some might expect array_filter on a collection to preserve arrays like it normally would.

All 4 comments

I would just run values on the Collection. Some might expect array_filter on a collection to preserve arrays like it normally would.

This might solve the problem @vespakoen mentioned:

$collection = collect($collection->values());

It takes out the values, and then make it a collection again.

This might solve the problem @vespakoen mentioned:

$collection = collect($collection->values());

It takes out the values, and then make it a collection again.

You save my day, man :P

This might solve the problem @vespakoen mentioned:

$collection = collect($collection->values());

It takes out the values, and then make it a collection again.

Laravel 5 and later returns a new Collection instance when running values. Because of that, running collect should _not_ be necessary. Resulting in;

$valuesCollection = $collection->values();
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jackmu95 picture jackmu95  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments

iivanov2 picture iivanov2  路  3Comments

felixsanz picture felixsanz  路  3Comments

SachinAgarwal1337 picture SachinAgarwal1337  路  3Comments