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

From: Date: Tue, 15 Feb 2022 14:07:36 +0000
Subject: Re: Setting to disable the "Undefined array index" warning
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-117041@lists.php.net to get a copy of this message
On 15/02/2022 12:54, Andreas Leathley wrote:
The problem with your way of writing code is that it is ambiguous in meaning, which is why this is a warning.
I think that's a good way of looking at it. There's actually quite a lot of code hiding a check like "if ($array['key'])"; roughly speaking, it's short-hand for: if ( array_key_exists('key', $array) && $array['key'] !== null && $array['key'] !== false && $array['key'] !== 0 && $array['key'] !== 0.0 && $array['key'] !== '' && $array['key'] !== [] ) Now, if that's what you intended, there's a syntax that's slightly more explicit while still being reasonably short: the empty() pseudo-function: if ( ! empty($array['key']) ) On the other hand, if what you actually meant was this: if ( array_key_exists('key', $array) && $array['key'] !== null ) Then you might have some bugs lurking, and actually want the isset() pseudo-function instead: if ( isset($array['key']) ) For other cases, you do have to spend a few more characters to be explicit, often using the "??" operator; for instance, if you expect $array['key'] to be either unset or a boolean, and want this: if ( array_key_exists('key', $array) && $array['key'] === true ) Then the shortest is probably something like this: if ( $array['key'] ?? false === true ) Regards, -- Rowan Tommins [IMSoP]

« previous php.internals (#117041) next »