PHP: What is the fastest and easiest way to get the last element of an array?

What is the fastest and easiest way to get the last element of an array, be it an indexed array, an associative array, or a multidimensional array?

+5
source share
6 answers
$myArray = array( 5, 4, 3, 2, 1 );

echo end($myArray);

prints "1"

+28
source

array_pop ()

It removes the element from the end of the array. If you need to keep the array in measure, you can use it and then add the value back to the end of the array.$array[] = $popped_val

+3
source

:

$arrayname[count(arrayname)-1]
+2

array_pop : array_pop

array_pop -

+1

. , :

function array_top(&$array) {
    $top = end($array);
    reset($array); // Optional
    return $top;
}

Alternatively, depending on your nature:

function array_top(&$array) {
    $top = array_pop($array);
    $array[] = $top; // Push top item back on top
    return $top;
}

( $array[] = ...preferred array_push(), see docs .)

+1
source

For an associative array:

$a= array('hi'=> 'there', 'ok'=> 'then');
list($k, $v) = array(end(array_keys($a)), end($a));
var_dump($k);
var_dump($v);

Edit: should also work with numeric index arrays

0
source

All Articles