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

当前回答

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

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

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

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

其他回答

我认为这是对所有现有答案的轻微改进:

$lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;

执行效果优于end()或使用array_keys()的解决方案,特别是对于大型数组 不会修改数组的内部指针 不会尝试访问空数组的未定义偏移量 将工作如预期的空数组,索引数组,混合数组,和关联数组

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

这个怎么样?

Eg-

$arr = [1,2,3];
$lastElem = count($arr) ? $arr[count($arr) - 1] : null;

我的简单解决方案,漂亮且容易理解。

array_reverse($array)[0];
$file_name_dm =  $_FILES["video"]["name"];    

                           $ext_thumb = extension($file_name_dm);

                            echo extension($file_name_dm); 
function extension($str){
    $str=implode("",explode("\\",$str));
    $str=explode(".",$str);
    $str=strtolower(end($str));
     return $str;
}