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

试着结束:

$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的数组)的语言例子。


我经常需要这个来处理堆栈,我总是发现自己困惑,没有本地函数在不以某种形式操作数组或其内部指针的情况下做到这一点。

因此,我通常携带一个util函数,它也可以安全地用于关联数组。

function array_last($array) {
    if (count($array) < 1)
        return null;

    $keys = array_keys($array);
    return $array[$keys[sizeof($keys) - 1]];
}

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

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

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

测试: 这样不行吗?

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

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

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

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

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

$lastValue = end(array_values($array))

不修改$array指针。这就避免了

reset($array)

这在某些情况下可能并不理想。


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

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


要做到这一点,避免E_STRICT,并且不混乱数组的内部指针,你可以使用:

function lelement($array) {return end($array);}

$last_element = lelement($array);

Lelement只适用于副本,所以它不会影响数组的指针。


从Array中获取最后一个值:

array_slice($arr,-1,1) ;

删除数组的最后一个值:

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

另一个解决方案:

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

又短又甜。

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

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

——之前的解决方案

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

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


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

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

$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_element = array_reverse( $array )[0];

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

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

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


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

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

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


对我来说:

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

associatives:

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

如何:

current(array_slice($array, -1))

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


这篇文章中的许多答案为我们提供了许多不同的选择。为了能够从中做出选择,我需要了解他们的行为和表现。在这个答案中,我将与您分享我的发现,以PHP版本5.6.38,7.2.10和7.3.0RC1为基准(预计2018年12月13日)。

我将测试的选项(<<选项代码>>s)是:

option .1. $x = array_values(array_slice($array, -1))[0]; (as suggested by rolacja) option .2. $x = array_slice($array, -1)[0]; (as suggested by Stoutie) option .3. $x = array_pop((array_slice($array, -1))); (as suggested by rolacja) option .4. $x = array_pop((array_slice($array, -1, 1))); (as suggested by Westy92) option .5. $x = end($array); reset($array); (as suggested by Iznogood) option .6. $x = end((array_values($array))); (as suggested by TecBrat) option .7. $x = $array[count($array)-1]; (as suggested by Mirko Pagliai) option .8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; (as suggested by thrau) option .9. $x = $array[] = array_pop($array); (as suggested by user2782001) option 10. $x = $array[array_key_last($array)]; (as suggested by Quasimodo's clone ; available per PHP 7.3)

(函数提到:array_key_last, array_keys, array_pop, array_slice, array_values, count, end, reset)

将测试输入(<<输入代码>>s)与:

Null = $array = Null; Empty = $array = []; Last_null = $array = ["a","b","c",null]; Auto_idx = $array = ["a","b","c","d"]; Shuffle = $array = [];$array[1] = "a";$array[2] = "b";$array[0] = "c"; 100 = $array = [];For ($i=0;$i<100;$i++) {$array[] = $i;} 100000 = $array = [];$i=0;$i<100000;$i++) {$array[] = $i;}

为了测试,我将使用5.6.38、7.2.10和7.3.0RC1 PHP docker容器,例如:

sudo docker run -it --rm php:5.6.38-cli-stretch php -r '<<<CODE HERE>>>'

上面列出的<<选项代码>>s和<<输入代码>>s的每个组合将在所有版本的PHP上运行。对于每个测试运行,使用以下代码片段:

<<input code>>  error_reporting(E_ALL);  <<option code>>  error_reporting(0); $before=microtime(TRUE); for($i=0;$i<100;$i++){echo ".";for($j=0;$j<100;$j++){  <<option code>>  }}; $after=microtime(TRUE); echo "\n"; var_dump($x); echo round(($after-$before)/(100*100)*1000*1000*1000);

对于每次运行,这将var_dump最后检索到的测试输入的最后一个值,并以飞秒为单位打印一次迭代的平均持续时间(0.000000000000001分之一秒)。

结果如下:

/==========================================================================================================================================================================================================================================================================================================================================================================================================================\
||                                                                      ||                            T  E  S  T     I  N  P  U  T     -     5  .  6  .  3  8                            ||                             T  E  S  T     I  N  P  U  T     -     7  .  2  .  1  0                           ||                             T  E  S  T     I  N  P  U  T     -     7  .  3  .  0  R  C  1                     ||
||                                                                      ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||
||============================OPTIONS - ERRORS==========================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||
||  2.  $x = array_slice($array, -1)[0];                                ||            W1 |            N1 |             - |             - |             - |             - |             - ||            W1 |            N1 |             - |             - |             - |             - |             - ||            W1 |            N1 |             - |             - |             - |             - |             - ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||       W1 + W3 |             - |             - |             - |             - |             - |             - ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||       W1 + W3 |             - |             - |             - |             - |             - |             - ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  5.  $x = end($array); reset($array);                                ||       W4 + W5 |             - |             - |             - |             - |             - |             - ||       W4 + W5 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||       W4 + W5 |             - |             - |             - |             - |             - |             - ||
||  6.  $x = end((array_values($array)));                               ||       W2 + W4 |             - |             - |             - |             - |             - |             - ||  W2 + N2 + W4 |             - |             - |             - |             - |             - |             - ||  W2 + N2 + W4 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  7.  $x = $array[count($array)-1];                                   ||             - |            N3 |             - |             - |             - |             - |             - ||            W7 |            N3 |             - |             - |             - |             - |             - ||            W7 |            N3 |             - |             - |             - |             - |             - ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||            W6 |       N3 + N4 |             - |             - |             - |             - |             - ||       W6 + W7 |       N3 + N4 |             - |             - |             - |             - |             - ||       W6 + W7 |       N3 + N4 |             - |             - |             - |             - |             - ||
||  9.  $x = $array[] = array_pop($array);                              ||            W3 |             - |             - |             - |             - |             - |             - ||            W3 |             - |             - |             - |             - |             - |             - ||            W3 |             - |             - |             - |             - |             - |             - ||
|| 10.  $x = $array[array_key_last($array)];                            ||            F1 |            F1 |            F1 |            F1 |            F1 |            F1 |            F1 ||            F2 |            F2 |            F2 |            F2 |            F2 |            F2 |            F2 ||            W8 |            N4 |            F2 |            F2 |            F2 |            F2 |            F2 ||
||========================OPTIONS - VALUE RETRIEVED=====================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  2.  $x = array_slice($array, -1)[0];                                ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  5.  $x = end($array); reset($array);                                ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  6.  $x = end((array_values($array)));                               ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  7.  $x = $array[count($array)-1];                                   ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  9.  $x = $array[] = array_pop($array);                              ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
|| 10.  $x = $array[array_key_last($array)];                            ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||
||=================OPTIONS - FEMTOSECONDS PER ITERATION=================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||           803 |           466 |           390 |           384 |           373 |           764 |     1.046.642 ||           691 |           252 |           101 |           128 |            93 |           170 |        89.028 ||           695 |           235 |            90 |            97 |            95 |           188 |        87.991 ||
||  2.  $x = array_slice($array, -1)[0];                                ||           414 |           349 |           252 |           248 |           246 |           604 |     1.038.074 ||           373 |           249 |            85 |            91 |            90 |           164 |        90.750 ||           367 |           224 |            78 |            85 |            80 |           155 |        86.141 ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||           724 |           228 |           323 |           318 |           350 |           673 |     1.042.263 ||           988 |           285 |           309 |           317 |           331 |           401 |        88.363 ||           877 |           266 |           298 |           300 |           326 |           403 |        87.279 ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||           734 |           266 |           358 |           356 |           349 |           699 |     1.050.101 ||           887 |           288 |           316 |           322 |           314 |           408 |        88.402 ||           935 |           268 |           335 |           315 |           313 |           403 |        86.445 ||
||  5.  $x = end($array); reset($array);                                ||           715 |           186 |           185 |           180 |           176 |           185 |           172 ||           674 |            73 |            69 |            70 |            66 |            65 |            70 ||           693 |            65 |            85 |            74 |            68 |            70 |            69 ||
||  6.  $x = end((array_values($array)));                               ||           877 |           205 |           320 |           337 |           304 |         2.901 |     7.921.860 ||           948 |           300 |           336 |           308 |           309 |           509 |    29.696.951 ||           946 |           262 |           301 |           309 |           302 |           499 |    29.234.928 ||
||  7.  $x = $array[count($array)-1];                                   ||           123 |           300 |           137 |           139 |           143 |           140 |           144 ||           312 |           218 |            48 |            53 |            45 |            47 |            51 ||           296 |           217 |            46 |            44 |            53 |            53 |            55 ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||           494 |           593 |           418 |           435 |           399 |         3.873 |    12.199.450 ||           665 |           407 |           103 |           109 |           114 |           431 |    30.053.730 ||           647 |           445 |            91 |            95 |            96 |           419 |    30.718.586 ||
||  9.  $x = $array[] = array_pop($array);                              ||           186 |           178 |           175 |           188 |           180 |           181 |           186 ||            83 |            78 |            75 |            71 |            74 |            69 |            83 ||            71 |            64 |            70 |            64 |            68 |            69 |            81 ||
|| 10.  $x = $array[array_key_last($array)];                            ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           370 |           223 |            49 |            52 |            61 |            57 |            52 ||
 \=========================================================================================================================================================================================================================================================================================================================================================================================================================/ 

上述“致命”、“警告”和“通知”代码翻译为:

F1 = Fatal error: Call to undefined function array_key_last() in Command line code on line 1
F2 = Fatal error: Uncaught Error: Call to undefined function array_key_last() in Command line code:1
W1 = Warning: array_slice() expects parameter 1 to be array, null given in Command line code on line 1
W2 = Warning: array_values() expects parameter 1 to be array, null given in Command line code on line 1
W3 = Warning: array_pop() expects parameter 1 to be array, null given in Command line code on line 1
W4 = Warning: end() expects parameter 1 to be array, null given in Command line code on line 1
W5 = Warning: reset() expects parameter 1 to be array, null given in Command line code on line 1
W6 = Warning: array_keys() expects parameter 1 to be array, null given in Command line code on line 1
W7 = Warning: count(): Parameter must be an array or an object that implements Countable in Command line code on line 1
W8 = Warning: array_key_last() expects parameter 1 to be array, null given in Command line code on line 1
N1 = Notice: Undefined offset: 0 in Command line code on line 1
N2 = Notice: Only variables should be passed by reference in Command line code on line 1
N3 = Notice: Undefined offset: -1 in Command line code on line 1
N4 = Notice: Undefined index:  in Command line code on line 1

基于这一输出,我得出以下结论:

newer versions of PHP perform better with the exception of these options that became significantly slower: option .6. $x = end((array_values($array))); option .8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; these options scale best for very large arrays: option .5. $x = end($array); reset($array); option .7. $x = $array[count($array)-1]; option .9. $x = $array[] = array_pop($array); option 10. $x = $array[array_key_last($array)]; (since PHP 7.3) these options should only be used for auto-indexed arrays: option .7. $x = $array[count($array)-1]; (due to use of count) option .9. $x = $array[] = array_pop($array); (due to assigning value losing original key) this option does not preserve the array's internal pointer option .5. $x = end($array); reset($array); this option is an attempt to modify option .5. to preserve the array's internal pointer (but sadly it does not scale well for very large arrays) option .6. $x = end((array_values($array))); the new array_key_last function seems to have none of the above mentioned limitations with the exception of still being an RC at the time of this writing (so use the RC or await it's release Dec 2018): option 10. $x = $array[array_key_last($array)]; (since PHP 7.3)

根据使用数组作为堆栈还是队列,你可以在选项9上做一些变化。


如果你不关心修改内部指针(以下行同时支持索引数组和关联数组):

// false if empty array
$last = end($array);

// null if empty array
$last = !empty($array) ? end($array) : null;

如果你想要一个不修改内部指针的实用函数(因为数组是按值传递给函数的,所以函数对它的副本进行操作):

function array_last($array) {
    if (empty($array)) {
        return null;
    }
    return end($array);
}

不过,PHP会“动态”地生成副本,即仅在实际需要时才生成副本。当end()函数修改数组时,会在内部生成整个数组(减去一项)的副本。

因此,我会推荐下面的替代方案,它实际上更快,因为在内部它不复制数组,它只是做一个切片:

function array_last($array) {
    if (empty($array)) {
        return null;
    }
    foreach (array_slice($array, -1) as $value) {
        return $value;
    }
}

此外,“foreach / return”是一个有效获取第一项(这里是单一项)的调整。

最后,最快的替代方法,但只适用于索引数组(并且没有空格):

$last = !empty($array) ? $array[count($array)-1] : null;


为了记录,这是我的另一个答案,对于数组的第一个元素。


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

PHP 7.3版引入了函数array_key_first和array_key_last。

由于PHP中的数组不是严格的数组类型,即从索引0开始的固定大小字段的固定大小集合,而是动态扩展的关联数组,因此处理具有未知键的位置很困难,而且变通方法执行得不好。相比之下,实数组将通过指针算术在内部快速寻址,并且在编译时通过声明已经知道最后一个索引。

至少从7.3版开始,第一个和最后一个位置的问题已经通过内置函数解决了。这甚至可以在没有任何警告的情况下对数组字面量开箱即用:

$first = array_key_first( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );
$last  = array_key_last ( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );

显然,最后一个值是:

$array[array_key_last($array)];

上面的答案很好,但是正如@paul-van-leeuwen和@quasimodos-clone所提到的,PHP 7.3将引入两个新函数来直接解决这个问题——array_key_first()和array_key_last()。

您现在就可以通过以下polyfill(或shim)函数开始使用此语法。

// Polyfill for array_key_last() available from PHP 7.3
if (!function_exists('array_key_last')) {
  function array_key_last($array) {
    return array_slice(array_keys($array),-1)[0];
  }
}

// Polyfill for array_key_first() available from PHP 7.3
if (!function_exists('array_key_first')) {
  function array_key_first($array) {
    return array_slice(array_keys($array),0)[0];
  }
}

// Usage examples:
$first_element_key   = array_key_first($array);
$first_element_value = $array[array_key_first($array)];

$last_element_key    = array_key_last($array);
$last_element_value  = $array[array_key_last($array)];

注意:这需要PHP 5.4或更高版本。


使用end()函数。

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

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

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

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

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


从PHP 7.3开始,array_key_last是可用的

$lastEl = $myArray[array_key_last($myArray)];

注意: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 = array('a', 'b', 'c', 'd');
echo ($array[count($array)-1]);

使用下面的逻辑,不仅可以得到最后一个元素,还可以得到第二个最后一个元素,第三个最后一个元素等等。

对于倒数第二个元素,你必须在上面的语句中只传递数字2,例如: 回声($阵列[count(数组)美元2]);


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

array_reverse($array)[0];

Array_values (array_reverse($array))[0]适用于所有这些情况。


这个怎么样?

Eg-

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

这里的大多数解决方案对于不关联的数组是不可靠的,因为如果我们有一个最后一个元素为false的不关联数组,那么end和current(array_slice($array, -1))也将返回false,因此我们不能使用false作为一个空的不关联数组的指示符。

// end returns false form empty arrays
>>> $arr = []
>>> end($arr)
=> false

// last element is false, so end returns false,
// now we'll have a false possitive that the array is empty
>>> $arr = [1, 2, 3, false]
>>> end($arr)
=> false

>>> $arr = [1, 2, 3, false, 4]
>>> end($arr)
=> 4

对于current(array_slice($arr, -1))也是一样:

// returns false form empty arrays
>>> $arr = []
>>> current(array_slice($arr, -1))
=> false

// returns false if last element is false
>>> $arr = [1, 2, 3, false]
>>> current(array_slice($arr, -1))
=> false

>>> $arr = [1, 2, 3, false, 4]
>>> current(array_slice($arr, -1))
=> 4

最好的选择是使用array_key_last,这适用于PHP >= 7.3.0或更老的版本,我们使用count来获取最后的索引(仅适用于未关联的数组):

// returns null for empty arrays
>>> $arr = []
>>> array_key_last($arr)
=> null

// returns last index of the array
>>> $arr = [1, 2, 3, false]
>>> array_key_last($arr)
=> 3

// returns last index of the array
>>> $arr = [1, 2, 3, false, 4]
>>> array_key_last($arr)
=> 4

对于旧版本,我们可以使用count:

>>> $arr = []
>>> if (count($arr) > 0) $arr[count($arr) - 1]
// No excecution

>>> $arr = [1, 2, 3, false]
>>> if (count($arr) > 0) $arr[count($arr) - 1]
=> false

>>> $arr = [1, 2, 3, false, 4]
>>> if (count($arr) > 0) $arr[count($arr) - 1]
=> 4

以上就是非关联数组的全部内容。如果我们确定我们有关联的数组,那么我们可以使用end。