Re: Two new functions array_first() and array_last()

From: Date: Tue, 17 Oct 2023 09:41:30 +0000
Subject: Re: Two new functions array_first() and array_last()
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to internals+get-121347@lists.php.net to get a copy of this message
On Tue, Oct 17, 2023 at 11:37 AM Robert Landers <landers.robert@gmail.com> wrote: > > On Tue, Oct 17, 2023 at 11:34 AM Aleksander Machniak <alec@alec.pl> wrote: > > > > On 17.10.2023 11:29, Robert Landers wrote: > > > $value = array_value_first($array, $key); > > > if($key === null) // handle error > > > else // do something with $value > > > > > > You can also freely ignore the key, if you don't need it or care about > > > error checking. That would save doing two function calls on the same > > > array, just to do some error checking. > > > > > > > Please, no. What's wrong with count() or empty()? > > > > +1 for array_first() and array_last(). The only problem is probably a > > big BC break. I myself have array_first() defined in my framework. > > > > -- > > Aleksander Machniak > > Kolab Groupware Developer [https://kolab.org] > > Roundcube Webmail Developer [https://roundcube.net] > > ---------------------------------------------------- > > PGP: 19359DC1 # Blog: https://kolabian.wordpress.com > > > > -- > > PHP Internals - PHP Runtime Development Mailing List > > To unsubscribe, visit: https://www.php.net/unsub.php > > > > Hey Aleksander, > > > Please, no. What's wrong with count() or empty()? > > Nothing. Why not either one? You don't have to use the $key variable > and you can use count() or empty(), but for me personally, it makes a > lot of sense. Ah, I just realized why it makes a lot of sense, and that is when Fibers get involved. The value and key could change underneath you from one function call to another. $key = array_key_first($this-array); // call something that suspends a fiber and results in $this->array being mutated $value = array_value_first($this->array); // $value and $key may now point to two totally separate things. I've been bitten by this with Fibers a few times now (or things very similar to it). Having a way to atomically get $key and $value would be a boon, not a hindrance. Robert Landers Software Engineer Utrecht NL

« previous php.internals (#121347) next »