r/PHPhelp • • Apr 12 '23

Bulk Fix for Undefined Array Key Issues

My team maintains a very old PHP codebase. The original developer wrote about a million lines of PHP code which rely on the fact that PHP will only raise a notice when you reference an undefined array key. In PHP 8.0 this was raised to a warning, filling our syslog with crud. We're upgrading to PHP 8.1 and so while we're doing refactoring to upgrade the codebase to support the new runtime, I want to take the time to clean this up.

I'm using Rector and I don't see a rule that will clean these up. I haven't found a php-cs-fixer rule or anything else out there either. Any advice on to change code like $foo = $_POST['bar']; to $foo = $_POST['bar'] ?? false;?

13 Upvotes

22 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Apr 12 '23

[deleted]

1

u/RandyHoward Apr 12 '23

What's fun is you can do something like this:

$value = $_POST[$key1] ?? $_POST[$key2] ?? $_POST[$key3] ?? FALSE;

$value will be the first key listed that is present in the $_POST, or false if none of them are present. Use this a lot in a scraper I maintain so I can cover legacy keys and new keys.