Make WordPress Core


Ignore:
Timestamp:
11/08/2021 01:50:35 PM (3 years ago)
Author:
hellofromTonya
Message:

General: Introduce polyfills for array_key_first() and array_key_last() added in PHP 7.3.0.

PHP 7.3.0 introduced two new functions: array_key_first() and array_key_last(). These two functions return the first and last key of each array respectively, without affecting the internal state of the array.

The polyfills make these two functions available for use in Core on PHP versions less than 7.3.0.

Ref:

Props desrosj, pbearne, costdev, hellofromTonya, ayeshrajans, manzoorwanijk, audrasjb, sergeybiryukov.
Fixes #45055.

File:
1 edited

Legend:

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

    r51853 r52038  
    376376}
    377377
     378if ( ! function_exists( 'array_key_first' ) ) {
     379    /**
     380     * Polyfill for array_key_first() function added in PHP 7.3.
     381     *
     382     * Get the first key of the given array without affecting
     383     * the internal array pointer.
     384     *
     385     * @since 5.9.0
     386     *
     387     * @param array $arr An array.
     388     * @return string|int|null The first key of array if the array
     389     *                         is not empty; `null` otherwise.
     390     */
     391    function array_key_first( array $arr ) {
     392        foreach ( $arr as $key => $value ) {
     393            return $key;
     394        }
     395    }
     396}
     397
     398if ( ! function_exists( 'array_key_last' ) ) {
     399    /**
     400     * Polyfill for `array_key_last()` function added in PHP 7.3.
     401     *
     402     * Get the last key of the given array without affecting the
     403     * internal array pointer.
     404     *
     405     * @since 5.9.0
     406     *
     407     * @param array $arr An array.
     408     * @return string|int|null The last key of array if the array
     409     *.                        is not empty; `null` otherwise.
     410     */
     411    function array_key_last( array $arr ) {
     412        if ( empty( $arr ) ) {
     413            return null;
     414        }
     415        end( $arr );
     416        return key( $arr );
     417    }
     418}
     419
    378420// IMAGETYPE_WEBP constant is only defined in PHP 7.1 or later.
    379421if ( ! defined( 'IMAGETYPE_WEBP' ) ) {
Note: See TracChangeset for help on using the changeset viewer.