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

Time:11-20

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,
   ]
>>> 

CodePudding user response:

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();

  • Related