好,
我知道所有array_pop(),但删除了最后一个元素.获取数组的最后一个元素而不删除它的最佳方法是什么?
编辑:这是一个奖金:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
Run Code Online (Sandbox Code Playgroud)
甚至
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice: Undefined offset: 2 in - on line 4
Run Code Online (Sandbox Code Playgroud)
Izn*_*ood 480
尝试
$myLastElement = end($yourArray);
Run Code Online (Sandbox Code Playgroud)
要重置它(感谢@hopeseekr):
reset($yourArray);
Run Code Online (Sandbox Code Playgroud)
链接到手册
@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
Run Code Online (Sandbox Code Playgroud)
谢谢o_O Tync和大家!
rol*_*cja 210
简短又甜蜜.
我想出了解决方案来删除错误消息并保留单行表单和高效性能:
$lastEl = array_values(array_slice($array, -1))[0];
Run Code Online (Sandbox Code Playgroud)
- 以前的解决方案
$lastEl = array_pop((array_slice($array, -1)));
Run Code Online (Sandbox Code Playgroud)
注意:需要额外的括号来避免a PHP Strict standards: Only variables should be passed by reference.
Pau*_*wen 111
这个帖子中的许多答案为我们提供了许多不同的选择.为了能够从中进行选择,我需要了解他们的行为和表现.在这个答案中,我将与您分享我的发现,以PHP版本为基准5.6.38,7.2.10以及7.3.0RC1(预计2018年12月13日).
<<option code>>我将测试的选项是:
$x = array_values(array_slice($array, -1))[0];(所建议的通过 rolacja)$x = array_slice($array, -1)[0];(所建议的通过 Stoutie)$x = array_pop((array_slice($array, -1)));(所建议的通过 rolacja)$x = array_pop((array_slice($array, -1, 1)));(所建议的通过 Westy92)$x = end($array); reset($array);(所建议的通过了Iznogood)$x = end((array_values($array)));(所建议的通过 TecBrat)$x = $array[count($array)-1];(由 Mirko Pagliai 建议)$keys = array_keys($array); $x = $array[$keys[count($keys)-1]];(所建议的通过 thrau)$x = $array[] = array_pop($array);(由 user2782001 建议)$x = $array[array_key_last($array)];(如建议由卡西莫多的克隆 ;每提供PHP 7.3)(functions mentioned: array_key_last , array_keys , array_pop , array_slice , array_values , count , end , reset)
The test inputs (<<input code>>s) to combine with:
$array = null;$array = [];$array = ["a","b","c",null];$array = ["a","b","c","d"];$array = []; $array[1] = "a"; $array[2] = "b"; $array[0] = "c";$array = []; for($i=0;$i<100;$i++) { $array[] = $i; }$array = []; for($i=0;$i<100000;$i++) { $array[] = $i; }For testing I will use the 5.6.38, 7.2.10 and 7.3.0RC1 PHP docker containers like:
sudo docker run -it --rm php:5.6.38-cli-stretch php -r '<<<CODE HERE>>>'
Run Code Online (Sandbox Code Playgroud)
Each combination of the above listed <<option code>>s and <<input code>>s will be run on all versions of PHP. For each test run the following code snippet is used:
<<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);
Run Code Online (Sandbox Code Playgroud)
For each run this will var_dump the last retrieved last value of the test input and print the average duration of one iteration in femtoseconds (0.000000000000001th of a second).
The results are as follows:
/==========================================================================================================================================================================================================================================================================================================================================================================================================================\
|| || 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 ||
\=========================================================================================================================================================================================================================================================================================================================================================================================================================/
Run Code Online (Sandbox Code Playgroud)
The above mentioned Fatal, Warning and Notice codes translate as:
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
Run Code Online (Sandbox Code Playgroud)
Based on this output I draw the following conclusions:
$x = end((array_values($array)));$keys = array_keys($array); $x = $array[$keys[count($keys)-1]];$x = end($array); reset($array);$x = $array[count($array)-1];$x = $array[] = array_pop($array);$x = $array[array_key_last($array)]; (since PHP 7.3)$x = $array[count($array)-1]; (due to use of count)$x = $array[] = array_pop($array); (due to assigning value losing original key)$x = end($array); reset($array);$x = end((array_values($array)));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):
$x = $array[array_key_last($array)]; (since PHP 7.3)A bit depending on whether using the array as stack or as queue you can make variations on option 9.
Sto*_*tie 35
怎么了array_slice($array, -1)?(见手册:http://us1.php.net/array_slice)
array_slice()返回一个数组.可能不是你想要的.你想要的元素.
War*_*rbo 20
避免传递引用错误的一种方法(例如"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))));
Run Code Online (Sandbox Code Playgroud)
Gra*_*ble 13
如果您不关心修改内部指针(支持索引和关联数组):
// false if empty array
$last = end($array);
// null if empty array
$last = !empty($array) ? end($array) : null;
Run Code Online (Sandbox Code Playgroud)
如果你想要一个不修改内部指针的实用程序函数(因为数组是按值传递的,并且函数在它的副本上运行):
function array_last($array) {
if (empty($array)) {
return null;
}
return end($array);
}
Run Code Online (Sandbox Code Playgroud)
请注意,PHP"即时"生成副本,即仅在实际需要时生成副本.它end()本身修改了数组,因此在内部生成了一个数组的副本.
因此,以下替代实际上更快,因为内部它不复制数组,它只是一个切片:
function array_last($array) {
if (empty($array)) {
return null;
}
foreach (array_slice($array, -1) as $value) {
return $value;
}
}
Run Code Online (Sandbox Code Playgroud)
这个"foreach/return"是一个有效获得第一个(和这里单个)项目的调整.
最后,最快的替代方案,但仅适用于索引数组:
$last = !empty($array) ? $array[count($array)-1] : null;
Run Code Online (Sandbox Code Playgroud)
对于记录,这是我的另一个答案,对于数组的第一个元素.
Tec*_*rat 10
未经测试:这不会起作用吗?
<?php
$last_element=end(array_values($array));
?>
Run Code Online (Sandbox Code Playgroud)
由于array_values返回的数组是短暂的,所以没有人关心它的指针是否被重置.
如果你需要钥匙,我想你会这样做:
<?php
$last_key=end(array_keys($array));
?>
Run Code Online (Sandbox Code Playgroud)
我经常需要这个来处理堆栈,而且我总是觉得自己很困惑,没有本机函数可以在没有以某种形式操纵数组或其内部指针的情况下执行它.
所以我通常带有一个util函数,它也可以安全地用在关联数组上.
function array_last($array) {
if (count($array) < 1)
return null;
$keys = array_keys($array);
return $array[$keys[sizeof($keys) - 1]];
}
Run Code Online (Sandbox Code Playgroud)
要获取数组的最后一个元素,请使用:
$lastElement = array_slice($array, -1)[0];
Run Code Online (Sandbox Code Playgroud)
基准
我迭代了1000次,分别抓住了包含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...
Run Code Online (Sandbox Code Playgroud)
我使用的是PHP版本5.5.32.
Aji*_*th 6
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
Run Code Online (Sandbox Code Playgroud)
小智 5
另一种可能的解决方案...
$last_element = array_reverse( $array )[0];
Run Code Online (Sandbox Code Playgroud)
从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 ] );
Run Code Online (Sandbox Code Playgroud)
显然,最后一个值是:
$array[array_key_last($array)];
Run Code Online (Sandbox Code Playgroud)
这个怎么样?
例如-
$arr = [1,2,3];
$lastElem = count($arr) ? $arr[count($arr) - 1] : null;
Run Code Online (Sandbox Code Playgroud)