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]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to