array_key_last

(PHP 7 >= 7.3.0)

array_key_lastGets the last key of an array

Descrição

array_key_last ( array $array ) : mixed

Get the last key of the given array without affecting the internal array pointer.

Parâmetros

array

An array.

Valor Retornado

Returns the last key of array if the array is not empty; NULL otherwise.

Veja Também

  • array_key_first() - Gets the first key of an array
  • end() - Faz o ponteiro interno de um array apontar para o seu último elemento
add a note add a note

User Contributed Notes 3 notes

up
9
Anyvie at devlibre dot fr
9 months ago
For PHP <= 7.3.0 :

if (! function_exists("array_key_last")) {
    function array_key_last($array) {
        if (!is_array($array) || empty($array)) {
            return NULL;
        }
       
        return array_keys($array)[count($array)-1];
    }
}
up
7
@manzoorwanijk
6 months ago
For PHP < 7.3.0 :

Will work for any type of array

<?php
if ( ! function_exists( 'array_key_last' ) ) {
   
/**
     * Polyfill for array_key_last() function added in PHP 7.3.
     *
     * Get the last key of the given array without affecting
     * the internal array pointer.
     *
     * @param array $array An array
     *
     * @return mixed The last key of array if the array is not empty; NULL otherwise.
     */
   
function array_key_last( $array ) {
       
$key = NULL;

        if (
is_array( $array ) ) {

           
end( $array );
           
$key = key( $array );
        }

        return
$key;
    }
}
?>
up
-1
wes at nospam dot example dot org
14 days ago
Correct polyfill (one that doesn't make copies of arrays, and that doesn't make use of the IAP) is:

<?php

if(!function_exists('array_key_first')){
    function
array_key_first(array $array){
        if(
$array === []){
            return
NULL;
        }
        foreach(
$array as $key => $_) return $key;
    }
}

if(!
function_exists('array_key_last')){
    function
array_key_last(array $array){
        if(
$array === []){
            return
NULL;
        }
        return
array_key_first(array_slice($array, -1));
    }
}

?>
To Top