Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does `reject()` method on a Laravel Collection return an associative array in this case?

Why does reject() transform the items in this collection into an associative array?

>>> collect([1, 2, 'X', 4])->reject('X')->all();
=> [
     0 => 1,
     1 => 2,
     3 => 3,
   ]
>>> 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

collect()->reject is built on collect()->filter, which in turn uses array_filter. (Arr::where is just an easy way to use the array_filter callback)

/**
 * Run a filter over each of the items.
 *
 * @param  callable|null  $callback
 * @return static
 */
public function filter(callable $callback = null)
{
    if ($callback) {
        return new static(Arr::where($this->items, $callback));
    }

    return new static(array_filter($this->items));
}

As mentioned in the documentation, Array keys are preserved, and may result in gaps if the array was indexed. The result array can be reindexed using the array_values() function. If there are no array keys specified, it uses the default 0->n. Collections apparently don’t remove the indexes when it comes back from array_values();

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading