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

From: Date: Wed, 20 Jun 2018 14:24:34 +0000
Subject: Re: [RFC][Under Discussion] Add functions array_key_first()and array_key_last()
References: 1 2 3 4 5 6 7 8 9  Groups: php.internals 
Request: Send a blank email to internals+get-102326@lists.php.net to get a copy of this message
On 20 June 2018 at 15:10, Levi Morrison <levim@php.net> wrote: > On Wed, Jun 20, 2018 at 8:09 AM Rowan Collins <rowan.collins@gmail.com> > wrote: > > > > On 20 June 2018 at 14:55, Levi Morrison <levim@php.net> wrote: > >> > >> > >> if ([$key, $value] = array_last($input) { > >> // do something > >> } > >> > > > > > > Unfortunately, this won't work. I didn't know list() could even be used > as an expression, but apparently if it is, it evaluates to the whole array > on its right-hand side, which makes sense. > > > > So, if array_last([]) returns [null, null], then [$key, > $value]=array_last([]) will also evaluate to [null, null]. Since that's not > an empty array (it has two elements in it), it will evaluate to true. > https://3v4l.org/lIEa1 > > > > If, on the other hand, array_last([]) returned something empty, like [], > the list() assignment would throw Notices for the implicit access to > elements [0] and [1] of the empty array. https://3v4l.org/qhq5R > > It returns ?array. So either > null or [$key, $value]. There are > no notices; sorry for the lack of detail. > Ah, OK, you learn something every day! For anyone else like me who was unaware of this, list() apparently silently accepts any non-array value on the right of the assignment, assigns all variables in the list() to null, and evaluates to the assigned (but otherwise unused) value. So $x=list($a,$b)=42; will set $a and $b to NULL, and $x to 42, without any notices. I don't think I would ever have expected that behaviour, but apparently it's been that way forever, so I guess it's fine to exploit it. Incidentally, there's no mention of this on the manual page, which is also missing information on the short-hand syntax and key-based destructuring introduced in PHP 7.1: http://php.net/list Regards, -- Rowan Collins [IMSoP]

« previous php.internals (#102326) next »