You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Collection的reject()方法为何在此场景下返回关联数组?

Why does Laravel Collection's reject() return an associative array in this scenario?

Let's break this down like we're debugging together—this is a super common gotcha with Laravel Collections, but once you get how they handle keys, it clicks right away.

First, let's recap your example

Your code:

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

Returns:

[0 => 1, 1 => 2, 3 => 4]

Question 1: Why does reject() result in an associative array here?

It’s not reject() directly spitting out an associative array—it’s a combination of how Collections preserve keys and how the all() method converts the Collection back to a PHP array.

When you create a Collection from a regular indexed array, every element keeps its original integer key (0, 1, 2, 3 in your case). When you call reject('X'), Laravel removes the element with value 'X' (which was at key 2) but doesn’t reset the keys of the remaining items. You’re left with a Collection holding keys 0, 1, 3—these aren’t a continuous zero-based sequence.

When you call all(), Laravel checks if the Collection’s keys form a seamless, zero-starting integer sequence. If they don’t (like your case), it returns an associative array to preserve the original key-value links.

Question 2: Why does reject() seem to convert elements to an associative array?

It’s not reject() doing the conversion—it’s preserving the original keys. If your filtered result had continuous keys, all() would return a regular indexed array. For example:

collect([1, 2, 3, 4])->reject(4)->all();
// Returns [1, 2, 3] (regular indexed array, since keys are 0,1,2)

Laravel Collections keep element keys intact by default during filtering operations like reject() or filter(). This is intentional—sometimes you need to track original positions or custom keys for your logic.

Want a regular indexed array instead?

Just chain the values() method before all() to reset the keys to a continuous zero-based sequence:

collect([1, 2, 'X', 4])->reject('X')->values()->all();
// Returns [1, 2, 4] (regular indexed array)

values() reindexes the Collection to use sequential integers starting at 0, so all() will spit out a non-associative array like you’d expect.

内容的提问来源于stack exchange,提问作者eysikal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:14:09