polyfill icon indicating copy to clipboard operation
polyfill copied to clipboard

[PHP 8.5] Add `array_first` and `array_last`

Open Ayesh opened this issue 6 months ago • 5 comments
trafficstars

Adds polyfills for the PHP 8.5's array_first and array_last functions.

The polyfills would have been a bit cleaner if we used the array_key_first and array_key_last functions, but they were added in PHP 7.3, and are not available on PHP 7.2.

This adds the same tests from php-src patch.

Ayesh avatar May 07 '25 07:05 Ayesh

I'm afraid that the current array_last implementation doesn't work with associative arrays. Indeed:

var_dump(array_slice(['a' => 2, 'b' => 1], -1, 1)[0]);

outputs a warning telling Undefined array key 0, whereas it should dump 1.

mtarld avatar May 09 '25 08:05 mtarld

I guess array_key_last should be used then

nicolas-grekas avatar May 09 '25 08:05 nicolas-grekas

@nicolas-grekas is it OK to bump the minimum PHP version to 7.3? If we have array_key_first/last, it would make this much more cleaner.

Ayesh avatar May 09 '25 08:05 Ayesh

Ah right, then current(array_slice()) should do it

nicolas-grekas avatar May 09 '25 08:05 nicolas-grekas

Updated with current(array_slice), and the other change suggestions from Nicolas. Thanks.

Ayesh avatar May 09 '25 10:05 Ayesh

is it OK to bump the minimum PHP version to 7.3? If we have array_key_first/last, it would make this much more cleaner.

We could depend on the polyfill-73 package

stof avatar Jun 23 '25 14:06 stof

Thank you @Ayesh.

nicolas-grekas avatar Jun 24 '25 07:06 nicolas-grekas

@nicolas-grekas I noticed this is not tagged yet. Could that be done 🙏 ?

ruudk avatar Aug 08 '25 11:08 ruudk