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

当前回答

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

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

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

其他回答

试着结束:

$myLastElement = end($yourArray);

注意,这不仅返回传递数组的最后一个元素,它还修改了数组的内部指针,current、each、prev和next都使用了这个指针。

对于PHP >= 7.3.0:

如果使用的是PHP 7.3.0或更高版本,可以使用array_key_last,它返回数组的最后一个键,而不修改其内部指针。要得到最后一个值,你可以这样做:

$myLastElement = $yourArray[array_key_last($yourArray)];

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

要获取数组的最后一个元素,使用:

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

基准

我迭代了1,000次,分别获取包含100个和50,000个元素的小型和大型数组的最后一个元素。

Method: $array[count($array)-1];
Small array (s): 0.000319957733154
Large array (s): 0.000526905059814
Note: Fastest!  count() must access an internal length property.
Note: This method only works if the array is naturally-keyed (0, 1, 2, ...).

Method: array_slice($array, -1)[0];
Small array (s): 0.00145292282104
Large array (s): 0.499367952347

Method: array_pop((array_slice($array, -1, 1)));
Small array (s): 0.00162816047668
Large array (s): 0.513121843338

Method: end($array);
Small array (s): 0.0028350353241
Large array (s): 4.81077480316
Note: Slowest...

我使用的是PHP 5.5.32版本。

对我来说:

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

associatives:

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

使用end()函数。

$array = [1,2,3,4,5];
$last = end($array); // 5