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

当前回答

在几乎每一种带有数组的语言中,使用A[A.size-1]都不会出错。我想不出一个基于1的数组(而不是基于0的数组)的语言例子。

其他回答

对我来说:

$last = $array[count($array) - 1];

associatives:

$last =array_values($array)[count($array - 1)]

测试: 这样不行吗?

<?php
$last_element=end(array_values($array));
?>

由于array_values返回的数组是稍纵即逝的,所以没有人关心它的指针是否被重置。

如果你需要钥匙的话,我猜你会这样做:

<?php
$last_key=end(array_keys($array));
?>

现在,我更喜欢一直有这个帮手,就像在php.net/end上建议的那样。

<?php
function endc($array) {
    return end($array);
}

$items = array('one','two','three');
$lastItem = endc($items); // three
$current = current($items); // one
?>

这将始终保持指针的原样,我们将永远不必担心括号,严格的标准或其他。

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

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

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

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
 }
}