Can I hide PHP Warning: Undefined array key without suppressing all other warnings?

Viewed 1791

So, looks like they changed the way accessing an array with an unknown key raises a message.

<?php
if($myArray['foo']) { ... }

For 25 years this was simply raising a NOTICE, and people were quite happy to silence E_NOTICE in php.ini. With (I think) PhP 8.0 this raises now a WARNING.

For obvious reason I don't want to silence E_WARNING, so I (and all the rest of the world who for years used uninitialized variables as their value was simply null, like in so many other interpreted language) was looking for a possible way to get rid of warnings related to undefined variables/arrays/keys while keep reported all the other (more serious) programming error, like including a non existing file.

Reason behind this question is that I have to deal with tons of code written with above pattern in mind; I just can't rewrite it all, but still I need to switch to PhP 8, so no, I'm not asking how to use isset().

2 Answers
set_error_handler(function(int $errno, string $errstr) {
    if ((strpos($errstr, 'Undefined array key') === false) && (strpos($errstr, 'Undefined variable') === false)) {
        return false;
    } else {
        return true;
    }
}, E_WARNING);

Use the Error Suppression operator @

<?php
if(@$myArray['foo']) { ... }

It's not as good as isset(), but at least it clearly says to the reader that you expect invalid indexes now and then.

Time has come to pay off your technical debt.

Related