Skip to content

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!

In order to review and merge PRs most efficiently, we require that all PRs grant maintainer edit access before we review them. For information on how to do this, see the relevant GitHub documentation. Additionally, GitHub doesn't allow maintainer permissions from organization accounts. Please resubmit this PR from a personal GitHub account with maintainer permissions enabled.

@github-actions github-actions bot closed this Apr 21, 2025
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

1 participant