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的严格标准:只有变量应该通过引用传递。

其他回答

如果你想让数组的最后一个元素在它的数组的循环中呢?

下面的代码将导致一个无限循环:

foreach ($array as $item) {
 $last_element = end($array);
 reset($array);
 if ($last_element == $item) {
   // something useful here
 }
}

对于非关联数组,解决方案显然很简单:

$last_element = $array[sizeof ($array) - 1];
foreach ($array as $key => $item) {
 if ($last_element == $item) {
   // something useful here
 }
}

简单地:$last_element = end((array_values($array)))

不重置数组,也不给出严格警告。

PS.由于投票最多的答案仍然没有双括号,所以我提交了这个答案。

避免引用传递错误的一种方法(例如。"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))));

另一个解决方案:

$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
$lastItem = $array[(array_keys($array)[(count($array)-1)])];
echo $lastItem;

从Array中获取最后一个值:

array_slice($arr,-1,1) ;

删除数组的最后一个值:

array_slice($arr,0,count($arr)-1) ;