On Monday, June 18, 2018 4:25:27 AM CDT Christoph M. Becker wrote:
> On 18.06.2018 at 00:09, Enno Woortmann wrote:
> > In my opinion that's the argument to return null for either parameters
> > which aren't an array or empty arrays simply because a first/last key
> > isn't present and null is the value to be returned for an undefined state.
> > I've tested this behavior with other array_* functions which are
> > provided in the PHP core and they provide null consistently, eg.:
> > 
> > root@WOL-Soft-DEVVM:/var/www/WOL-Soft# php -r "var_dump(array_keys(1));"
> > PHP Warning:  array_keys() expects parameter 1 to be array, integer
> > given in Command line code on line 1
> > NULL
> > root@WOL-Soft-DEVVM:/var/www/WOL-Soft# php -r
> > "var_dump(array_values('hello'));"
> > PHP Warning:  array_values() expects parameter 1 to be array, string
> > given in Command line code on line 1
> > NULL
> > root@WOL-Soft-DEVVM:/var/www/WOL-Soft# php -r
> > "var_dump(array_flip(null));"
> > PHP Warning:  array_flip() expects parameter 1 to be array, null given
> > in Command line code on line 1
> > NULL
> 
> These return values are due to zend_parse_parameters() failures (i.e.
> the given types don't match the expected types), and it's customary to
> return NULL in this case (under strict typing an exception would be
> thrown instead).  However, most functions signal other failures by
> returning FALSE, for instance:
> 
>   var_dump(array_search('foo', [])); // => bool(false)
> 
> I would prefer, if these other functions would return NULL, though, but
> we can't change that for BC reasons.

Returning false for "not found" rather than "null" is a big middle-finger to 
users. :-)  Besides the reasons here, the violation of type constraints 
totally screws up the surrounding code.  Especially with null-coalesce.  For 
instance, this thing of beauty:

$secret = getenv('APP_SECRET') 
  ?? $_SERVER['APP_SECRET'] 
  ?? getenv('DEFAULT_SECRET')
;

doesn't actually work, because getenv() returns false instead of null.  
Instead you have to do this mess:

$secret = (getenv('APP_SECRET') ?: null)
        ?? $_SERVER['APP_SECRET']
        ?? (getenv('DEFAULT_SECRET') ?: null)
    ;

See also:

https://www.garfieldtech.com/blog/empty-return-values

Can we please never return false for error/not-found, ever, period, forever 
more?  It's a fundamentally broken idiom that needs to die.

--Larry Garfield

Attachment: signature.asc
Description: This is a digitally signed message part.

Reply via email to