Skip to content

The value collection method shouldn't consider 0 as null #54910

@phadaphunk

Description

@phadaphunk

Laravel Version

12.x

PHP Version

8.3.15

Database Driver & Version

No response

Description

From the documentation on the value() collection method

The value method retrieves a given value from the first element of the collection

0 Should not be treated as null so the check should be specifically against null.

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

$collection->value("balance");

// 200

I would expect to get Tim's debt based on the doc.

Even more so in this case,

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

$collection->where('name', 'Tim')->value("balance");

// null

Same goes for all values that evaluate the same way.

$collection = collect([
  ["name" => "Tim", "vegetarian" => false],
  ["name" => "John", "vegetarian" => true]
]);

$collection->value('vegetarian');

// true

Or even a "0" string.

Steps To Reproduce

Run this code

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

$collection->value("balance");

// 200

In a scenario like this, skipping a user because his balance is 0 feels wrong. The access pattern might not be the best but it's just an example of a real use case.

I know it is probably handled that way because of how PHP handles zero values but I feel this is the kind of gotcha that can be confusing to new developers using Laravel.

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions