Ok,

我知道所有关于array_pop(),但它删除了最后一个元素。如何获得数组的最后一个元素而不删除它?

这里有一个奖励:

$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');

甚至

$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice:  Undefined offset:  2 in - on line 4

当前回答

又短又甜。

我想出了一个解决方案来删除错误信息,并保留一行程序形式和高效性能:

$lastEl = array_values(array_slice($array, -1))[0];

——之前的解决方案

$lastEl = array_pop((array_slice($array, -1)));

注意:额外的括号是为了避免PHP的严格标准:只有变量应该通过引用传递。

其他回答

避免引用传递错误的一种方法(例如。"end(array_values($foo))")是使用call_user_func或call_user_func_array:

// PHP Fatal error: Only variables can be passed by reference
// No output (500 server error)
var_dump(end(array(1, 2, 3)));

// No errors, but modifies the array's internal pointer
// Outputs "int(3)"
var_dump(call_user_func('end', array(1, 2, 3)));

// PHP Strict standards:  Only variables should be passed by reference
// Outputs "int(3)"
var_dump(end(array_values(array(1, 2, 3))));

// No errors, doesn't change the array
// Outputs "int(3)"
var_dump(call_user_func('end', array_values(array(1, 2, 3))));

End()将提供数组的最后一个元素

$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
echo end($array); //output: c

$array1 = array('a', 'b', 'c', 'd');
echo end($array1); //output: d

注意:For (PHP 7 >= 7.3.0) 我们可以用 array_key_last -获取数组的最后一个键

array_key_last ( array $array ) : mixed

裁判:http://php.net/manual/en/function.array-key-last.php

array_slice($array, -1)有什么问题?(参见手册:http://us1.php.net/array_slice)

Array_slice()返回一个数组。可能不是你想要的。你想要元素。

如何:

current(array_slice($array, -1))

适用于关联数组 当$array ==[](返回false)时生效 不会影响原始数组