Re: Setting to disable the "Undefined array index" warning

From: Date: Tue, 15 Feb 2022 12:54:16 +0000
Subject: Re: Setting to disable the "Undefined array index" warning
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-117038@lists.php.net to get a copy of this message
On 15.02.22 13:31, Nicolas BADIA wrote:
As it is explained in this ticket https://bugs.php.net/bug.php?id=81417 we use to check if a property exists by accessing it directly like we do in JavaScript. Personally, I subscribe to this coding style and we use it all over our codebase (more than 130 000 lines of PHP code). When it became a notice, we disabled them, but now that it is a warning, it is a lot more problematic for us… We can’t even use the last version of PHP Debug for VSCode.
The problem with your way of writing code is that it is ambiguous in meaning, which is why this is a warning. You are not checking if a key in an array exists, you are checking if an array value is "false-y". If the value is an empty string, it is also interpreted as false, if it is null, it is also interpreted as false, if it is an integer of value zero it is also interpreted as false, if it is the string "0" it is also interpreted as false. When you write code as you do, it is easy to introduce subtle errors because of these implicit casts. If you want to check if an array key is defined, you should do it explicitly - this is not about a "coding style", this is about writing the code in a way that actually does what you intend it to do without it meaning multiple things of which some are probably not expected. If you just want a quick fix without solving the underlying problem, you can just add "?? null" to each array key access. If you want to upgrade/improve your code base, which is a worthwhile task, I would suggest the use of a static analyzer (like Psalm or PHPStan) to find out where your code is ambigious. I have found many undetected errors that way, where implicit casts have lead to unexpected outcomes, which is why I am very much in favor of these warnings for undefined array keys.

« previous php.internals (#117038) next »