On 15/02/2022 15:12, Guilliam Xavier wrote:
On Tue, Feb 15, 2022 at 3:07 PM Rowan Tommins <[email protected]>
wrote:
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'
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!
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 undefined
Ah, 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]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php