Skip to content

Improvement handle falsy values in collections #55512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

lokeshrangani
Copy link

Purpose

This PR adds a new valuePreservingFalsy method to Laravel Collections that safely retrieves a value for a given key without discarding falsy values like 0, false, '0', or an empty array.
Benefit to End Users

The existing value() method internally uses firstWhere(), which stops on the first truthy match—excluding valid falsy values such as 0 and false. This new method ensures that these legitimate values are preserved and returned when present.
Backward Compatibility

This is a new method, so it does not affect any existing functionality or break backward compatibility.
Tests Included
Example

$collection = collect([
['name' => 'Tim', 'balance' => 0],
['name' => 'John', 'balance' => 200],
]);

$collection->valuePreservingFalsy('balance'); // returns 0

Test coverage for all major PHP falsy values:

0 (int)
0.0 (float)
'0' (string)
false
[] (empty array)
null
'' (empty string)

Related Issue

Closes #54910

Copy link

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@shaedrich
Copy link
Contributor

shaedrich commented Apr 23, 2025

The name of your new method is quite a mouthful. Is there a reason, you didn't add this behavior as a flag to the existing value() method, targeting master rather than 12.x as done in #55499?

@lokeshrangani lokeshrangani changed the base branch from 12.x to master April 28, 2025 14:11
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.

The value collection method shouldn't consider 0 as null
2 participants