Re: [RFC][Under Discussion] Add functions array_key_first()and array_key_last()

From: Date: Wed, 20 Jun 2018 16:02:59 +0000
Subject: Re: [RFC][Under Discussion] Add functions array_key_first()and array_key_last()
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to internals+get-102329@lists.php.net to get a copy of this message
Am 20.06.2018 um 15:55 schrieb Levi Morrison:
Your wish cannot be granted for array_value_last and array_value_first; you cannot know by itself if there is a failure condition.
I can comprehend your issue with the lack of distinctness between the error case and the 'real' array value null without further checks. But in my opinion the required additional checking of the $input is a learned behaviour from existing functions which handle single value elements from an array as reset(), current() and end() will return false for empty arrays or null for invalid data types which are both also valid element values. array_pop() and array_shift() also behave in a comparable way as they return null as well for empty arrays as for non array input.
This is not "clean". In contrast here is with my proposal:
     if ([$key, $value] = array_last($input) {
         // do something
     }
I still think that this proposed syntax is unintuitive and hard to comprehend for the user of the function.
I don't think many PHP developers out there know that the condition inside the if will evaluate to null if array_last returns null. Additionally I don't know about any other function where a construct like this has to be used to extract two or more different semantic entities, in this case the key and the value, out of a PHP core function return value. Enno

« previous php.internals (#102329) next »