首页 文章

获取数组的最后一个元素而不删除它的最佳方法是什么?

提问于
浏览
338

好,

我知道所有关于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

24 回答

  • 10

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

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

    Benchmark

    我迭代了1000次,分别 grab 了包含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 .

  • 1

    另一种可能的解决方案

    $last_element = array_reverse( $array )[0];
    
  • 1

    我认为这对所有现有答案都略有改进:

    $lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;
    
    • 使用 array_keys() 执行优于 end() 或解决方案,特别是对于大型数组

    • 赢了't modify the array'的内部指针

    • 不会尝试访问空数组的未定义偏移量

    • 将按预期为空数组,索引数组,混合数组和关联数组工作

  • 3
    $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;
    }
    
  • 1

    如果您不关心修改内部指针(支持索引和关联数组):

    // 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($value);
    }
    

    请注意,PHP生成副本"on-the-fly",即仅在实际需要时 . 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;
    
  • 79

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

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

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

  • 1

    要做到这一点并避免使用E_STRICT而不是弄乱阵列的内部指针,您可以使用:

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

    lelement只能与副本一起使用,因此它不会影响数组的指针 .

  • 0
    $lastValue = end(array_values($array))
    

    没有修改$ array指针 . 这避免了

    reset($array)
    

    在某些条件下可能不需要 .

  • 441

    另一种方案:

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

    怎么样:

    current(array_slice($array, -1))
    
    • 适用于关联数组

    • $array == [] (返回 false )时有效

    • 不会影响原始数组

  • 1

    为了我:

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

    使用关联:

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

    最好的答案很棒,但正如@ 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或更高版本 .

  • -3

    从PHP 7.3版开始,引入了函数 array_key_firstarray_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)];
    
  • 157

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

    不重置阵列,也不会发出STRICT警告 .

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

  • 5

    在几乎所有带阵列的语言中,A [A.size-1]都不会出错 . 我想不出一个基于1个数组的语言的例子(而不是基于零的) .

  • 6

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

    如果你想在它的数组循环中得到数组的最后一个元素怎么办?

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

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

    尝试

    $myLastElement = end($yourArray);
    

    要重置它(感谢@hopeseekr):

    reset($yourArray);
    

    链接到manual

    @David Murdoch补充道: $myLastElement = end(array_values($yourArray));// and now you don't need to call reset(). 在E_STRICT上,这会产生警告

    Strict Standards: Only variables should be passed by reference
    

    谢谢o_O Tync和大家!

  • 2

    我经常需要这个来处理堆栈,而且我总是觉得自己很困惑,没有本机函数可以在没有以某种形式操纵数组或其内部指针的情况下执行它 .

    所以我通常带有一个util函数,它也可以安全地用在关联数组上 .

    function array_last($array) {
        if (count($array) < 1)
            return null;
    
        $keys = array_keys($array);
        return $array[$keys[sizeof($keys) - 1]];
    }
    
  • 8

    这个帖子中的许多答案为我们提供了许多不同的选择 . 成为能够从中选择我需要了解他们的行为和表现 . 在这个答案中,我将与您分享我的发现,以PHP版本 5.6.387.2.107.3.0RC1expected Dec 13 2018)为基准 .

    我将测试的选项( <<option code>> s)是:

    • option .1. $x = array_values(array_slice($array, -1))[0];

    • option .2. $x = array_slice($array, -1)[0];

    • option .3. $x = array_pop((array_slice($array, -1)));

    • option .4. $x = array_pop((array_slice($array, -1, 1)));

    • option .5. $x = end($array); reset($array);

    • option .6. $x = end((array_values($array)));

    • option .7. $x = $array[count($array)-1];

    • 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;根据PHP 7.3提供)

    测试输入( <<input code>> 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 = []; for($i=0;$i<100000;$i++) { $array[] = $i; }

    为了测试,我将使用 5.6.387.2.107.3.0RC1 docker容器,如:

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

    上面列出的 <<option code>><<input code>> 的每个组合都将在所有版本的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最后检索的测试输入的最后一个值,并打印一次迭代的平均持续时间in femtoseconds(0.000000000000001th of of second) .

    结果如下:

    /==========================================================================================================================================================================================================================================================================================================================================================================================================================\
    ||                                                                      ||                            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 ||
     \=========================================================================================================================================================================================================================================================================================================================================================================================================================/
    

    上面提到的 F atal, W arning和 N otice代码翻译为:

    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
    

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

    • 较新版本的PHP表现更好,但这些选项变得非常慢:

    • option .6. $x = end((array_values($array)));

    • option .8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]];

    • 这些选项最适合非常大的数组:

    • 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)]; (自PHP 7.3起)

    • 这些选项应 only be used for auto-indexed arrays

    • option .7. $x = $array[count($array)-1]; (由于使用 count

    • option .9. $x = $array[] = array_pop($array); (由于分配值丢失原始密钥)

    • 此选项 does not preserve the array's internal pointer

    • option .5. $x = end($array); reset($array);

    • 此选项试图修改 option .5. 以保留数组的内部指针(但遗憾的是,对于非常大的数组,它不能很好地扩展)

    • option .6. $x = end((array_values($array)));

    • array_key_last 函数似乎没有上述限制,但在撰写本文时仍然是RC(因此请使用RC或等待它发布于2018年12月):

    • option 10. $x = $array[array_key_last($array)]; (自PHP 7.3起)

    有点取决于using the array as stack or as queue你是否可以在选项9上做出变化 .

  • 33

    要从Array获取最后一个值:

    array_slice($arr,-1,1) ;
    

    对于删除最后一个值表单数组:

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

    未经测试:这不会起作用吗?

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

    由于array_values返回的数组是短暂的,所以没有人关心它的指针是否被重置 .

    如果你需要钥匙,我想你会这样做:

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

    简短又甜蜜 .

    我想出了解决方案来删除错误消息并保留单行表单和高效性能:

    $lastEl = array_values(array_slice($array, -1))[0];
    
    • 以前的解决方案
    $lastEl = array_pop((array_slice($array, -1)));
    

    注意:需要额外的括号来避免 PHP Strict standards: Only variables should be passed by reference .

相关问题