Skip to content

[13.x] Fix Collection::mode() returning wrong results for float values#60721

Open
Amirhf1 wants to merge 1 commit into
laravel:13.xfrom
Amirhf1:fix/collection-mode-float-precision
Open

[13.x] Fix Collection::mode() returning wrong results for float values#60721
Amirhf1 wants to merge 1 commit into
laravel:13.xfrom
Amirhf1:fix/collection-mode-float-precision

Conversation

@Amirhf1

@Amirhf1 Amirhf1 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Collection::mode() (and LazyCollection::mode(), which just delegates to it) gives you the wrong answer when your collection has float values in it.

Why

The method counts occurrences by using each value directly as an array key:

$collection->each(fn ($value) => $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1);

The problem is PHP silently truncates float array keys down to integers. So if you have distinct floats that happen to share the same integer part, they get lumped together into one bucket:

(new Collection([1.5, 1.5, 1.9, 2.9, 2.9, 2.9]))->mode();
// Expected: [2.9] (it shows up 3 times)
// Actual:   [1, 2] (wrong, and these numbers aren't even in the original array!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant