Make WordPress Core

Changeset 60672


Ignore:
Timestamp:
08/26/2025 09:29:47 PM (2 months ago)
Author:
jorbin
Message:

General: Add polyfills for new PHP 8.5 array functions: array_first and array_last.

This power couple of function is coming in PHP 8.5: array_first and array_last.

For more information on these functions, check out the PHP RFC at https://wiki.php.net/rfc/array_first_last.

Props tusharbharti, jorbin, peterwilsoncc, mukesh27, johnbillion.
Fixes #63853. See #63061.

Location:
trunk
Files:
2 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/compat.php

    r60312 r60672  
    540540}
    541541
     542if ( ! function_exists( 'array_first' ) ) {
     543    /**
     544     * Polyfill for `array_first()` function added in PHP 8.5.
     545     *
     546     * Returns the first element of an array.
     547     *
     548     * @since 6.9.0
     549     *
     550     * @param array $array The array to get the first element from.
     551     * @return mixed|null The first element of the array, or null if the array is empty.
     552     */
     553    function array_first( array $array ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound
     554        if ( empty( $array ) ) {
     555            return null;
     556        }
     557
     558        foreach ( $array as $value ) {
     559            return $value;
     560        }
     561    }
     562}
     563
     564if ( ! function_exists( 'array_last' ) ) {
     565    /**
     566     * Polyfill for `array_last()` function added in PHP 8.5.
     567     *
     568     * Returns the last element of an array.
     569     *
     570     * @since 6.9.0
     571     *
     572     * @param array $array The array to get the last element from.
     573     * @return mixed|null The last element of the array, or null if the array is empty.
     574     */
     575    function array_last( array $array ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound
     576        if ( empty( $array ) ) {
     577            return null;
     578        }
     579
     580        return $array[ array_key_last( $array ) ];
     581    }
     582}
     583
    542584// IMAGETYPE_AVIF constant is only defined in PHP 8.x or later.
    543585if ( ! defined( 'IMAGETYPE_AVIF' ) ) {
Note: See TracChangeset for help on using the changeset viewer.