WordPress.org

Make WordPress Core

Opened 13 months ago

Last modified 9 months ago

#45055 new feature request

Introduce new PHP cross-version compatibility functions, `array_key_first()`, `array_key_last()`

Reported by: desrosj Owned by:
Milestone: Future Release Priority: normal
Severity: normal Version: 5.1
Component: General Keywords: php73 has-patch
Focuses: Cc:
PR Number:

Description

PHP 7.3 will introduce two new functions, array_key_first(), and array_key_last(). The two functions return the first and last key of each array respectively, without affecting the internal state of the array (reset(), end() and key() do). The full RFC can be read here: https://wiki.php.net/rfc/array_key_first_last

Including a polyfill would allow developers to take advantage of the new functions and write consistent code regardless of a site's PHP version. While polyfills for these two functions are not required for WordPress to be PHP 7.3 compatible, it could be added in the version after 7.3 compatibility is declared.

Attachments (2)

45055.diff (1.3 KB) - added by manzoorwani.jk 12 months ago.
45055-2-optimized.patch (5.0 KB) - added by ayeshrajans 9 months ago.

Download all attachments as: .zip

Change History (6)

#2 @desrosj
12 months ago

  • Keywords php73 added

#3 @manzoorwani.jk
12 months ago

For array_key_first, foreach is faster than reset while as for array_key_last, end is faster than other approaches like array_slice or array_keys with end.

#4 @ayeshrajans
9 months ago

  • Keywords has-patch added; needs-patch removed
  • Version set to trunk

I also think it's a good idea to add the polyfills, but also to search existing current(), reset(), and key() calls to make use of this function. I know PHP 7.3 users will appreciate it too.

Patch from @manzoorwanijk is a good start, but now that PHP 7.3 is released, we can make it more closure to the native function. It looks like this patch was taken from the first example in this function page. Symfony/polyfills has a better one that mimics the original functionality with parameter types. I will attach a patch with more optimized polyfills. To make it complete, this patch also contains the original tests from PHP source, so we can make sure it really gives same results as PHP's own tests.

Note: See TracTickets for help on using tickets.