Re: Setting to disable the "Undefined array index" warning
| From: | Rowan Tommins | Date: | Tue, 15 Feb 2022 15:50:48 +0000 |
| Subject: | Re: Setting to disable the "Undefined array index" warning | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-117043@lists.php.net to get a copy of this message | ||
On 15/02/2022 15:12, Guilliam Xavier wrote:
On Tue, Feb 15, 2022 at 3:07 PM Rowan Tommins <rowan.collins@gmail.com> wrote:Ah yes, that one really demonstrates the dangers of type juggling in general. If it _wasn't_ considered empty, that would be inconsistent with how integer juggling works, but it definitely catches people out!if ( array_key_exists('key', $array) && $array['key'] !== null && $array['key'] !== false && $array['key'] !== 0 && $array['key'] !== 0.0 && $array['key'] !== '' && $array['key'] !== [] )Agreed, but you forgot the most "annoying": && $array['key'] !== '0'
Mind operator precedence! This is interpreted as: if ( $array['key'] ?? (false === true) ) (obviously not intended), so you need explicit parentheses: if ( ($array['key'] ?? false) === true )Oops, I admit I didn't test that. That does make the operator somewhat less attractive, and maybe it would be more straight-forward to just be explicit: if ( isset($array['key']) && $array['key'] === true )
I will also note that the "shorthands" (!empty(), isset(), ?? null) will also "hide" another warning when the $array variable itself is undefinedAh, yes, so they do; as does the ?? operator, for that matter. I seem to remember someone proposing an explicit operator for "this array dimension might not exist", something like this: if ( $array[?'key'] === true ) Which would translate to: if ( (array_key_exists('key', $array) ? $array['key'] : null) === true ) Regards, -- Rowan Tommins [IMSoP]