On Tue, Feb 15, 2022 at 3:07 PM Rowan Tommins <rowan.coll...@gmail.com>
wrote:

> 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'] !== [] )
>

Agreed, but you forgot the most "annoying":

&& $array['key'] !== '0'


> 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 )
>

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 )


I will also note that the "shorthands" (!empty(), isset(), ?? null) will
also "hide" another warning when the $array variable itself is undefined

Reply via email to