Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 什么';获取数组的最后一个元素而不删除它的最佳方法是什么?_Php_Arrays - Fatal编程技术网

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

Php 什么';获取数组的最后一个元素而不删除它的最佳方法是什么?,php,arrays,Php,Arrays,嗯 我完全知道,但这会删除最后一个元素。获取数组的最后一个元素而不删除它的最佳方法是什么 编辑:这里有一个奖励: $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:

我完全知道,但这会删除最后一个元素。获取数组的最后一个元素而不删除它的最佳方法是什么

编辑:这里有一个奖励:

$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
试一试

要重置它(感谢@hopeseekr):

链接到

@大卫·默多克补充道:
$MyLasteElement=end(数组_值($yourArray));//现在不需要调用reset()。
在E_STRICT上,这会产生警告

Strict Standards: Only variables should be passed by reference

谢谢你和所有人

我经常需要它来处理堆栈,我总是发现自己很困惑,没有一个本机函数可以不以某种形式操纵数组或其内部指针就完成它

所以我通常带着一个util函数,在关联数组上使用它也是安全的

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

    $keys = array_keys($array);
    return $array[$keys[sizeof($keys) - 1]];
}
函数数组\u last($array){
if(计数($array)<1)
返回null;
$keys=数组\ U键($array);
返回$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
 }
}
// false if empty array
$last = end($array);

// null if empty array
$last = !empty($array) ? end($array) : null;
未经测试: 这不管用吗

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

由于数组_值返回的数组是短暂的,因此没有人关心它的指针是否重置

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

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

避免传递引用错误的一种方法(例如“end(array\u values($foo)))是使用call\u user\u func或call\u user\u func\u数组:

// 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))));
未对$array指针进行任何修改。这避免了

reset($array)

在某些情况下可能不需要。

数组片($array,-1)有什么问题?(见手册:)


array\u slice()
返回一个数组。可能不是你想要的。您需要元素。

来执行此操作,避免E_严格,并且不会弄乱数组的内部指针,您可以使用:

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

$last_element = lelement($array);

leElement仅与副本一起使用,因此不会影响数组的指针。

要从数组中获取最后一个值:

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
array_key_last ( array $array ) : mixed

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

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

我迭代了1000次,分别获取了包含100个和50000个元素的大小数组的最后一个元素

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\u element=end((数组值($array)))

不会重置阵列,也不会给出严格的警告


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

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

$lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;
  • 性能优于
    end()
    或使用
    array\u keys()
    的解决方案,尤其是对于大型阵列
  • 不会修改数组的内部指针
  • 不会尝试访问空数组的未定义偏移量
  • 将按预期工作于空数组、索引数组、混合数组和关联数组
    • 对我来说:

      $last = $array[count($array) - 1];
      
      使用联想词:

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

      current(array_slice($array, -1))
      
      • 适用于关联数组
      • $array=[]
        时工作(返回
        false
      • 不影响原始数组

        • 本帖中的许多答案为我们提供了许多不同的选择。为了能够从他们中选择,我需要了解他们的行为和表现。在这个答案中,我将与您分享我的发现,这些发现是以PHP版本
          5.6.38
          7.2.10
          7.3.0RC1
          ()为基准的

          我将测试的选项(
          s)有:

          • 选项。1.
            $x=array\u值(array\u切片($array,-1))[0](由)
          • 选项。2.
            $x=array\u slice($array,-1)[0](由)
          • 选项。3.
            $x=array\u pop((array\u slice($array,-1))(由)
          • 选项。4.
            $x=array\u pop((array\u slice($array,-1,1))(由)
          • 选项。5.
            $x=end($array);重置($阵列)(由)
          • 选项。6.
            $x=end((数组_值($array))(由)
          • 选项。7.
            $x=$array[计数($array)-1](由)
          • 选项。8.
            $keys=array\u keys($array)$x=$array[$keys[计数($keys)-1]](由)
          • 选项9.
            $x=$array[]=array\u pop($array)(由)
          • 选项10.
            $x=$array[数组\键\最后一个($array)](由;可根据PHP7.3获得)
          (提到的功能:,,,,,,)

          测试输入(
          s)要与以下内容结合:

          • null=
            $array=null
          • =
            $array=[]
          • last_null=
            $array=[“a”、“b”、“c”、null]
          • auto_idx=
            $array=[“a”、“b”、“c”、“d”]
          • 洗牌=
            $array=[]$数组[1]=“a”$数组[2]=“b”$数组[0]=“c”

          • 100=
            $array=[];对于($i=0;$i),如果您不关心修改内部指针(以下几行同时支持索引数组和关联数组):


            如果您想要一个不修改内部指针的实用程序函数(因为数组是按值传递给函数的,所以函数在其副本上操作):


            current(array_slice($array, -1))
            sudo docker run -it --rm php:5.6.38-cli-stretch php -r '<<<CODE HERE>>>'
            
            <<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);
            
            /==========================================================================================================================================================================================================================================================================================================================================================================================================================\
            ||                                                                      ||                            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
            
            // 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);
            }
            
            function array_last($array) {
                if (empty($array)) {
                    return null;
                }
                foreach (array_slice($array, -1) as $value) {
                    return $value;
                }
            }
            
            $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;
            }
            
            $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)];
            
            // 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)];
            
            $array = [1,2,3,4,5];
            $last = end($array); // 5
            
            <?php
            function endc($array) {
                return end($array);
            }
            
            $items = array('one','two','three');
            $lastItem = endc($items); // three
            $current = current($items); // one
            ?>
            
            $lastEl = $myArray[array_key_last($myArray)];
            
            array_key_last ( array $array ) : mixed
            
            $array = array('a', 'b', 'c', 'd');
            echo ($array[count($array)-1]);
            
            array_reverse($array)[0];
            
            $arr = [1,2,3];
            $arr[count($arr) - 1]