Framework: isset called on a collection where the value is null returns true

Created on 6 Mar 2020  路  5Comments  路  Source: laravel/framework

  • Laravel Version: Any, but tested on 6.x
  • PHP Version: any
  • Database Driver & Version: N/A

Description:

When calling isset($collection['key']) I believe the expected behaviour should be the same as that for isset($array['key']). That is, if the value is null, isset should return false. Currently, it returns true.

This happens because the offsetExists implementation on Collection uses array_key_exists rather than isset() (and isset itself relies on offsetExists for objects that implement ArrayAccess).

Note: I only noticed this once on PHP 7.4, which emits a notice when you try to use array access on a non-array value (in this case null).

Steps To Reproduce:

$arr = ['a' => null];
$coll = new Illuminate\Support\Collection($arr);

dd(isset($arr['a']), isset($coll['a']));

// false
// true

This eval reproduces the behaviour in a minimal environment:

https://3v4l.org/7Um54

Additional Notes

If the current behaviour is the expected behaviour, we should document this.

I created this as a bug report first just to make sure that we do in fact want this behaviour to match the regular array behaviour, as this would technically be a breaking change. I am happy to submit a PR to fix this once confirmed as a bug, or submit a PR to the docs if it is deemed behaviour as intended.

bug

Most helpful comment

@nunomaduro Not it's not. It's only deprecated on objects. @phroggyy was talking about how that function behaves on the array inside the laravel collection.

All 5 comments

I'd agree that this is a bug. isset is meant to return false when something "is set" but "is null".

Worth to mention that array_key_exist is deprecated: https://www.php.net/manual/en/migration74.deprecated.php

@nunomaduro Not it's not. It's only deprecated on objects. @phroggyy was talking about how that function behaves on the array inside the laravel collection.

As it seems to be agreed this is a bug, I will submit a PR for this later this afternoon.

This will be fixed in Laravel 8

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CupOfTea696 picture CupOfTea696  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

digirew picture digirew  路  3Comments

shopblocks picture shopblocks  路  3Comments

YannPl picture YannPl  路  3Comments