Ok,
好吧,
I know all about array_pop()
, but that deletes the last element. What's the best way to get the last element of an array without deleting it?
我知道所有关于array_pop()的内容,但是它删除了最后一个元素。不删除数组的最后一个元素的最好方法是什么?
EDIT: Here's a bonus:
编辑:这里有一个好处:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
or even
甚至
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice: Undefined offset: 2 in - on line 4
22 个解决方案
#1
121
Short and sweet.
短暂而甜蜜的。
I came up with solution to remove error message and preserve one-liner form and efficient performance:
我提出了一种解决方案,可以消除错误信息,保持一行的形式和高效的性能:
$lastEl = array_values(array_slice($array, -1))[0];
-- previous solution
——以前的解决方案
$lastEl = array_pop((array_slice($array, -1)));
Note: The extra parentheses are needed to avoid a PHP Strict standards: Only variables should be passed by reference
.
注意:需要额外的括号来避免PHP严格的标准:仅通过引用传递变量。
#2
410
Try
试一试
$myLastElement = end($yourArray);
To reset it (thanks @hopeseekr):
重置(感谢@hopeseekr):
reset($yourArray);
Link to manual
链接到手册
@David Murdoch added: $myLastElement = end(array_values($yourArray));// and now you don't need to call reset().
On E_STRICT this produces the warning
@David Murdoch添加:$myLastElement = end(array_values($yourArray));//现在您不需要调用reset()。在E_STRICT上,这会产生警告。
Strict Standards: Only variables should be passed by reference
Thanks o_O Tync and everyone!
谢谢大家!
#3
54
The many answers in this thread present us with many different options. To be able to choose from them I needed to understand their behavior and performance. In this answer I will share my findings with you, benchmarked against PHP versions 5.6.29
and 7.1.0
. The options I will test are:
这个线程中的许多答案为我们提供了许多不同的选项。要从他们中做出选择,我需要了解他们的行为和表现。在这个答案中,我将与您分享我的发现,以PHP版本5.6.29和7.1.0为基准。我将测试的选项是:
-
option 1.
$x = array_values(array_slice($array, -1))[0];
- 选项1。$ x =元素(array_slice($数组,1))[0];
-
option 2.
$x = array_slice($array, -1)[0];
- 第二个选项。$ x = array_slice($数组,1)[0];
-
option 3.
$x = array_pop((array_slice($array, -1)));
- 选项3。$ x =最后(array_slice($数组,1)));
-
option 4.
$x = array_pop((array_slice($array, -1, 1)));
- 选项4。$x = array_pop(array_slice($array, - 1,1));
-
option 5.
$x = end($array); reset($array);
- 选择5。$ x =结束(数组);重置(数组);
-
option 6.
$x = end((array_values($array)));
- 选择6。$ x =结束(元素(数组)美元));
-
option 7.
$x = $array[count($array)-1];
- 选择7。$ x = $数组(count($数组)1);
-
option 8.
$keys = array_keys($array); $x = $array[$keys[count($keys)-1]];
- 选择8。数组键=中的美元(美元);美元$ x = $ array[键[count(键)美元1]];
-
option 9.
$x = $array[] = array_pop($array);
- 选择9。$x = $array[] = array_pop($array);
Test inputs:
测试输入:
-
null =
$array = null;
- null = $array = null;
-
empty =
$array = [];
- 空= $array = [];
-
last_null =
$array = ["a","b","c",null];
- last_null = $array = ["a","b","c",null];
-
auto_idx =
$array = ["a","b","c","d"];
- auto_idx = $array = ["a"、"b"、"c"、"d"];
-
shuffle =
$array = []; $array[1] = "a"; $array[2] = "b"; $array[0] = "c";
- 洗牌= $array = [];数组美元[1]= " ";数组美元[2]=“b”;数组美元[0]= " c ";
-
100 =
$array = []; for($i=0;$i<100;$i++) { $array[] = $i; }
- 100 = $array = [];为($i=0;$i<100;$i+) {$ $array[] = $i;}
-
100000 =
$array = []; for($i=0;$i<100000;$i++) { $array[] = $i; }
- 100000 = $array = [];$i=0;$i<100000;$i+) {$ $array[] = $i;}
For testing I will use the 5.6.29
and 7.1.0
docker containers like:
对于测试,我将使用5.6.29和7.1.0 docker容器,如:
sudo docker run -it --rm php:5.6.29-cli php -r '<<<CODE HERE>>>'
Each combination of the above listed <<option code>>
s, the above listed test <<input code>>
s will be run on both versions of PHP. For each test run the following code snippet is used:
上面列出的每一个组合都将在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<1;$j++){ <<option code>> }}; $after=microtime(TRUE); echo "\n"; var_dump($x); echo round(($after-$before)*10);
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 nanoseconds.
对于每次运行,这将var_dump测试输入的最后一个检索值,并以纳秒为单位打印一次迭代的平均持续时间。
The results are as follows:
结果如下:
/=======================================================================================================================================================================================================================================================================================================\
|| || T E S T I N P U T - 5 . 6 . 2 9 || T E S T I N P U T - 7 . 1 . 0 ||
|| || 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 | - | - | - | - | - ||
|| 2. $x = array_slice($array, -1)[0]; || W1 | N1 | - | - | - | - | - || W1 | N1 | - | - | - | - | - ||
|| 3. $x = array_pop((array_slice($array, -1))); || W1 + W3 | - | - | - | - | - | - || 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 ||
|| 5. $x = end($array); reset($array); || W4 + W5 | - | - | - | - | - | - || W4 + W5 | - | - | - | - | - | - ||
|| 6. $x = end((array_values($array))); || W2 + W4 | - | - | - | - | - | - || W2 + N2 + W4 | N2 | N2 | N2 | N2 | N2 | N2 ||
|| 7. $x = $array[count($array)-1]; || - | N3 | - | - | - | - | - || - | N3 | - | - | - | - | - ||
|| 8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; || W5 | N3 + N4 | - | - | - | - | - || W5 | N3 + N4 | - | - | - | - | - ||
|| 9. $x = $array[] = array_pop($array); || W3 | - | - | - | - | - | - || W3 | - | - | - | - | - | - ||
||=======================OPTIONS - VALUE RETRIEVED=====================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
|| 1. $x = array_values(array_slice($array, -1))[0]; || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 2. $x = array_slice($array, -1)[0]; || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 3. $x = array_pop((array_slice($array, -1))); || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 4. $x = array_pop((array_slice($array, -1, 1))); || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 5. $x = end($array); reset($array); || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 6. $x = end((array_values($array))); || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 7. $x = $array[count($array)-1]; || NULL | NULL | NULL | string(1) "d" | string(1) "b" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "b" | int(99) | int(9999999) ||
|| 8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 9. $x = $array[] = array_pop($array); || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
||================OPTIONS - NANOSECONDS PER ITERATION==================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
|| 1. $x = array_values(array_slice($array, -1))[0]; || 681 | 413 | 320 | 321 | 317 | 649 | 1.034.200 || 642 | 231 | 102 | 110 | 105 | 174 | 86.700 ||
|| 2. $x = array_slice($array, -1)[0]; || 362 | 301 | 206 | 205 | 202 | 530 | 1.006.000 || 329 | 205 | 63 | 67 | 65 | 134 | 87.000 ||
|| 3. $x = array_pop((array_slice($array, -1))); || 671 | 183 | 273 | 273 | 269 | 597 | 997.200 || 807 | 244 | 282 | 305 | 285 | 355 | 87.300 ||
|| 4. $x = array_pop((array_slice($array, -1, 1))); || 687 | 206 | 303 | 305 | 294 | 625 | 1.003.600 || 812 | 249 | 284 | 288 | 287 | 359 | 87.200 ||
|| 5. $x = end($array); reset($array); || 671 | 136 | 137 | 140 | 137 | 137 | 139 || 632 | 43 | 45 | 46 | 45 | 45 | 45 ||
|| 6. $x = end((array_values($array))); || 674 | 156 | 278 | 278 | 257 | 2.934 | 8.464.000 || 835 | 239 | 270 | 274 | 265 | 474 | 815.000 ||
|| 7. $x = $array[count($array)-1]; || 90 | 257 | 102 | 101 | 101 | 106 | 102 || 31 | 190 | 32 | 34 | 35 | 32 | 32 ||
|| 8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; || 420 | 543 | 365 | 369 | 334 | 3.498 | 12.190.000 || 358 | 373 | 90 | 97 | 89 | 333 | 1.322.000 ||
|| 9. $x = $array[] = array_pop($array); || 145 | 150 | 144 | 144 | 143 | 144 | 143 || 46 | 46 | 46 | 49 | 48 | 46 | 47 ||
\=======================================================================================================================================================================================================================================================================================================/
The above mentioned Warning and Notice codes translate as:
上述警告和通知代码翻译为:
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
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
Based on this output I draw the following conclusions:
基于此,我得出以下结论:
- use a newer version of PHP when possible (duh)
- 尽可能使用更新的PHP版本(duh)
- for large arrays the options are limited to:
- either option 5.
$x = end($array); reset($array);
- 要么选择5。$ x =结束(数组);重置(数组);
- or option 7.
$x = $array[count($array)-1];
- 或选择7。$ x = $数组(count($数组)1);
- or option 9.
$x = $array[] = array_pop($array);
- 或选择9。$x = $array[] = array_pop($array);
- either option 5.
- 对于大型数组,选项被限制为:选项5。$ x =结束(数组);重置(数组);或选择7。$ x = $数组(count($数组)1);或选择9。$x = $array[] = array_pop($array);
- for non-auto-indexed arrays, options 7 and 9 are not an option
- 对于非自动索引的数组,选项7和9不是选项
Personally I do not like concerning myself with array internal pointers and prefer a solution in a single expression. Therefore short story I would myself use:
就我个人而言,我不喜欢使用数组内部指针,而喜欢使用单个表达式中的解决方案。因此,我要用我自己的短篇故事:
- for auto-indexed arrays:
- either option 7.
$x = $array[count($array)-1];
- 要么选择7。$ x = $数组(count($数组)1);
- or option 9.
$x = $array[] = array_pop($array);
- 或选择9。$x = $array[] = array_pop($array);
- either option 7.
- 对于自动索引数组:任意选项7。$ x = $数组(count($数组)1);或选择9。$x = $array[] = array_pop($array);
-
for non-auto-indexed arrays:(invalid)-
option 9.$x = $array[] = array_pop($array);
- 选择9。$x = $array[] = array_pop($array);
-
- 对于非自动索引的数组:(无效)选项9。$x = $array[] = array_pop($array);
A bit depending on whether using the array as stack or as queue you can make variations on option 9.
这取决于是否使用数组作为堆栈或作为队列,您可以对选项9进行更改。
#4
32
What's wrong with array_slice($array, -1)
? (See Manual: http://us1.php.net/array_slice)
array_slice($array, -1)有什么问题?(见手册:http://us1.php.net/array_slice)
array_slice()
returns an array. Probably not what you are looking for. You want the element.
array_slice()返回一个数组。可能不是你想要的。你想要的元素。
#5
18
One way to avoid pass-by-reference errors (eg. "end(array_values($foo))") is to use call_user_func or call_user_func_array:
避免引用传递错误的一种方法。“结束(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))));
#6
10
untested: wouldn't this work?
未经考验的:不是这个工作?
<?php
$last_element=end(array_values($array));
?>
Since the array returned by array_values is fleeting, no-one cares if it's pointer is reset.
由于array_values返回的数组是转瞬即逝的,所以没有人关心它的指针是否被重置。
and if you need the key to go with it I guess you'd do:
如果你需要钥匙,我猜你会这么做:
<?php
$last_key=end(array_keys($array));
?>
#7
8
I need this quite often to deal with stacks, and i always find myself baffled that there's no native function that does it without manipulating the array or its internal pointer in some form.
我经常需要它来处理堆栈,我总是发现如果不以某种形式操作数组或它的内部指针,就没有本地函数来处理堆栈,这让我很困惑。
So i usually carry around a util function that's also safe to use on associative arrays.
所以我通常携带一个util函数它在关联数组中也是安全的。
function array_last($array) {
if (count($array) < 1)
return null;
$keys = array_keys($array);
return $array[$keys[sizeof($keys) - 1]];
}
#8
6
end() will provide the last element of an array
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
#9
5
If you don't care about modifying the internal pointer (supports both indexed and associative arrays):
如果您不关心修改内部指针(支持索引数组和关联数组):
// false if empty array
$last = end($array);
// null if empty array
$last = !empty($array) ? end($array) : null;
If you want a utility function that doesn't modify the internal pointer:
如果你想要一个不修改内部指针的效用函数:
function array_last($array) {
if (empty($array)) {
return null;
}
return end($value);
}
The original array's internal pointer is not modified, because the array is copied.
原始数组的内部指针没有被修改,因为数组被复制了。
Thus, the following alternative is actually faster as it doesn't copy the array, it just makes a slice:
因此,下面的选择实际上更快,因为它不复制数组,它只做一个切片:
function array_last($array) {
if (empty($array)) {
return null;
}
foreach (array_slice($array, -1) as $value) {
return $value;
}
}
This "foreach / return" is a tweak for efficiently getting the first (and here single) item.
这个“foreach / return”是有效获取第一个(这里是单个)条目的一个调整。
Finally, the fastest alternative but for indexed arrays only:
最后,除了索引数组之外,最快的选择是:
$last = !empty($array) ? $array[count($array)-1] : null;
#10
5
To get the last element of an array, use:
要获取数组的最后一个元素,请使用:
$lastElement = array_slice($array, -1)[0];
Benchmark
基准
I iterated 1,000 times, grabbing the last element of small and large arrays that contained 100 and 50,000 elements, respectively.
我迭代了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...
I used PHP Version 5.5.32.
我使用的是PHP 5.5.32。
#11
3
For me:
对我来说:
$last = $array[count($array) - 1];
With associatives:
associatives:
$last =array_values($array)[count($array - 1)]
#12
2
To do this and avoid the E_STRICT and not mess with the array's internal pointer you can use:
要做到这一点,并避免E_STRICT和不要打乱数组的内部指针,您可以使用:
function lelement($array) {return end($array);}
$last_element = lelement($array);
lelement only works with a copy so it doesn't affect the array's pointer.
lelement只对复制起作用,因此不会影响数组的指针。
#13
2
Another solution:
另一个解决方案:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
$lastItem = $array[(array_keys($array)[(count($array)-1)])];
echo $lastItem;
#14
1
$lastValue = end(array_values($array))
No modification is made to $array pointers. This avoids the
没有对$array指针进行修改。这样就避免了
reset($array)
which might not be desired in certain conditions.
这在某些情况下是不可取的。
#15
1
For getting the last value from Array :
从数组中获取最后一个值:
array_slice($arr,-1,1) ;
For Removing last value form array :
用于删除最后一个值表单数组:
array_slice($arr,0,count($arr)-1) ;
#16
1
Simply: $last_element = end((array_values($array)))
简单:$ last_element =结束(元素(数组)美元))
Doesn't reset the array and doesn't gives STRICT warnings.
不会重置数组,也不会发出严格的警告。
PS. Since the most voted answer still hasn't the double parenthesis, I submitted this answer.
因为大多数投票的答案仍然没有双括号,所以我提交了这个答案。
#17
1
One more possible solution...
一个可能的解决方案……
$last_element = array_reverse( $array )[0];
#18
1
How about:
如何:
current(array_slice($array, -1))
- works for associative arrays
- 适用于关联数组
- works when
$array == []
(returnsfalse
) - 当$array ==[]时工作(返回false)
- doesn't affect the original array
- 不会影响原始数组。
#19
1
I think this is a slight improvement on all the existing answers:
我认为这是对现有答案的一个小小的改进:
$lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;
- Performs better than
end()
or solutions usingarray_keys()
, especially with large arrays - 使用array_keys()比end()或解决方案执行得更好,特别是对于大型数组
- Won't modify the array's internal pointer
- 不会修改数组的内部指针
- Won't try to access an undefined offset for empty arrays
- 不会尝试访问空数组的未定义偏移量
- Will work as expected for empty arrays, indexed arrays, mixed arrays, and associative arrays
- 对于空数组、索引数组、混合数组和关联数组,是否可以正常工作?
#20
0
What if you want to get the last element of array inside of the loop of it's array?
如果你想在数组的循环中得到数组的最后一个元素呢?
The code below will result into an infinite loop:
下面的代码将导致一个无限循环:
foreach ($array as $item) {
$last_element = end($array);
reset($array);
if ($last_element == $item) {
// something useful here
}
}
The solution is obviously simple for non associative arrays:
对于非关联数组,解决方案显然很简单:
$last_element = $array[sizeof ($array) - 1];
foreach ($array as $key => $item) {
if ($last_element == $item) {
// something useful here
}
}
#21
0
$file_name_dm = $_FILES["video"]["name"];
$ext_thumb = extension($file_name_dm);
echo extension($file_name_dm);
function extension($str){
$str=implode("",explode("\\",$str));
$str=explode(".",$str);
$str=strtolower(end($str));
return $str;
}
#22
-3
In almost every language with arrays you can't really go wrong with A[A.size-1]. I can't think of an example of a language with 1 based arrays (as opposed to zero based).
在几乎每一种使用数组的语言中,您都不能真正出错[A.size-1]。我想不出一种基于数组(而不是基于0)的语言的例子。
#1
121
Short and sweet.
短暂而甜蜜的。
I came up with solution to remove error message and preserve one-liner form and efficient performance:
我提出了一种解决方案,可以消除错误信息,保持一行的形式和高效的性能:
$lastEl = array_values(array_slice($array, -1))[0];
-- previous solution
——以前的解决方案
$lastEl = array_pop((array_slice($array, -1)));
Note: The extra parentheses are needed to avoid a PHP Strict standards: Only variables should be passed by reference
.
注意:需要额外的括号来避免PHP严格的标准:仅通过引用传递变量。
#2
410
Try
试一试
$myLastElement = end($yourArray);
To reset it (thanks @hopeseekr):
重置(感谢@hopeseekr):
reset($yourArray);
Link to manual
链接到手册
@David Murdoch added: $myLastElement = end(array_values($yourArray));// and now you don't need to call reset().
On E_STRICT this produces the warning
@David Murdoch添加:$myLastElement = end(array_values($yourArray));//现在您不需要调用reset()。在E_STRICT上,这会产生警告。
Strict Standards: Only variables should be passed by reference
Thanks o_O Tync and everyone!
谢谢大家!
#3
54
The many answers in this thread present us with many different options. To be able to choose from them I needed to understand their behavior and performance. In this answer I will share my findings with you, benchmarked against PHP versions 5.6.29
and 7.1.0
. The options I will test are:
这个线程中的许多答案为我们提供了许多不同的选项。要从他们中做出选择,我需要了解他们的行为和表现。在这个答案中,我将与您分享我的发现,以PHP版本5.6.29和7.1.0为基准。我将测试的选项是:
-
option 1.
$x = array_values(array_slice($array, -1))[0];
- 选项1。$ x =元素(array_slice($数组,1))[0];
-
option 2.
$x = array_slice($array, -1)[0];
- 第二个选项。$ x = array_slice($数组,1)[0];
-
option 3.
$x = array_pop((array_slice($array, -1)));
- 选项3。$ x =最后(array_slice($数组,1)));
-
option 4.
$x = array_pop((array_slice($array, -1, 1)));
- 选项4。$x = array_pop(array_slice($array, - 1,1));
-
option 5.
$x = end($array); reset($array);
- 选择5。$ x =结束(数组);重置(数组);
-
option 6.
$x = end((array_values($array)));
- 选择6。$ x =结束(元素(数组)美元));
-
option 7.
$x = $array[count($array)-1];
- 选择7。$ x = $数组(count($数组)1);
-
option 8.
$keys = array_keys($array); $x = $array[$keys[count($keys)-1]];
- 选择8。数组键=中的美元(美元);美元$ x = $ array[键[count(键)美元1]];
-
option 9.
$x = $array[] = array_pop($array);
- 选择9。$x = $array[] = array_pop($array);
Test inputs:
测试输入:
-
null =
$array = null;
- null = $array = null;
-
empty =
$array = [];
- 空= $array = [];
-
last_null =
$array = ["a","b","c",null];
- last_null = $array = ["a","b","c",null];
-
auto_idx =
$array = ["a","b","c","d"];
- auto_idx = $array = ["a"、"b"、"c"、"d"];
-
shuffle =
$array = []; $array[1] = "a"; $array[2] = "b"; $array[0] = "c";
- 洗牌= $array = [];数组美元[1]= " ";数组美元[2]=“b”;数组美元[0]= " c ";
-
100 =
$array = []; for($i=0;$i<100;$i++) { $array[] = $i; }
- 100 = $array = [];为($i=0;$i<100;$i+) {$ $array[] = $i;}
-
100000 =
$array = []; for($i=0;$i<100000;$i++) { $array[] = $i; }
- 100000 = $array = [];$i=0;$i<100000;$i+) {$ $array[] = $i;}
For testing I will use the 5.6.29
and 7.1.0
docker containers like:
对于测试,我将使用5.6.29和7.1.0 docker容器,如:
sudo docker run -it --rm php:5.6.29-cli php -r '<<<CODE HERE>>>'
Each combination of the above listed <<option code>>
s, the above listed test <<input code>>
s will be run on both versions of PHP. For each test run the following code snippet is used:
上面列出的每一个组合都将在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<1;$j++){ <<option code>> }}; $after=microtime(TRUE); echo "\n"; var_dump($x); echo round(($after-$before)*10);
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 nanoseconds.
对于每次运行,这将var_dump测试输入的最后一个检索值,并以纳秒为单位打印一次迭代的平均持续时间。
The results are as follows:
结果如下:
/=======================================================================================================================================================================================================================================================================================================\
|| || T E S T I N P U T - 5 . 6 . 2 9 || T E S T I N P U T - 7 . 1 . 0 ||
|| || 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 | - | - | - | - | - ||
|| 2. $x = array_slice($array, -1)[0]; || W1 | N1 | - | - | - | - | - || W1 | N1 | - | - | - | - | - ||
|| 3. $x = array_pop((array_slice($array, -1))); || W1 + W3 | - | - | - | - | - | - || 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 ||
|| 5. $x = end($array); reset($array); || W4 + W5 | - | - | - | - | - | - || W4 + W5 | - | - | - | - | - | - ||
|| 6. $x = end((array_values($array))); || W2 + W4 | - | - | - | - | - | - || W2 + N2 + W4 | N2 | N2 | N2 | N2 | N2 | N2 ||
|| 7. $x = $array[count($array)-1]; || - | N3 | - | - | - | - | - || - | N3 | - | - | - | - | - ||
|| 8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; || W5 | N3 + N4 | - | - | - | - | - || W5 | N3 + N4 | - | - | - | - | - ||
|| 9. $x = $array[] = array_pop($array); || W3 | - | - | - | - | - | - || W3 | - | - | - | - | - | - ||
||=======================OPTIONS - VALUE RETRIEVED=====================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
|| 1. $x = array_values(array_slice($array, -1))[0]; || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 2. $x = array_slice($array, -1)[0]; || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 3. $x = array_pop((array_slice($array, -1))); || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 4. $x = array_pop((array_slice($array, -1, 1))); || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 5. $x = end($array); reset($array); || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 6. $x = end((array_values($array))); || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | bool(false) | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 7. $x = $array[count($array)-1]; || NULL | NULL | NULL | string(1) "d" | string(1) "b" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "b" | int(99) | int(9999999) ||
|| 8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
|| 9. $x = $array[] = array_pop($array); || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) || NULL | NULL | NULL | string(1) "d" | string(1) "c" | int(99) | int(9999999) ||
||================OPTIONS - NANOSECONDS PER ITERATION==================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
|| 1. $x = array_values(array_slice($array, -1))[0]; || 681 | 413 | 320 | 321 | 317 | 649 | 1.034.200 || 642 | 231 | 102 | 110 | 105 | 174 | 86.700 ||
|| 2. $x = array_slice($array, -1)[0]; || 362 | 301 | 206 | 205 | 202 | 530 | 1.006.000 || 329 | 205 | 63 | 67 | 65 | 134 | 87.000 ||
|| 3. $x = array_pop((array_slice($array, -1))); || 671 | 183 | 273 | 273 | 269 | 597 | 997.200 || 807 | 244 | 282 | 305 | 285 | 355 | 87.300 ||
|| 4. $x = array_pop((array_slice($array, -1, 1))); || 687 | 206 | 303 | 305 | 294 | 625 | 1.003.600 || 812 | 249 | 284 | 288 | 287 | 359 | 87.200 ||
|| 5. $x = end($array); reset($array); || 671 | 136 | 137 | 140 | 137 | 137 | 139 || 632 | 43 | 45 | 46 | 45 | 45 | 45 ||
|| 6. $x = end((array_values($array))); || 674 | 156 | 278 | 278 | 257 | 2.934 | 8.464.000 || 835 | 239 | 270 | 274 | 265 | 474 | 815.000 ||
|| 7. $x = $array[count($array)-1]; || 90 | 257 | 102 | 101 | 101 | 106 | 102 || 31 | 190 | 32 | 34 | 35 | 32 | 32 ||
|| 8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; || 420 | 543 | 365 | 369 | 334 | 3.498 | 12.190.000 || 358 | 373 | 90 | 97 | 89 | 333 | 1.322.000 ||
|| 9. $x = $array[] = array_pop($array); || 145 | 150 | 144 | 144 | 143 | 144 | 143 || 46 | 46 | 46 | 49 | 48 | 46 | 47 ||
\=======================================================================================================================================================================================================================================================================================================/
The above mentioned Warning and Notice codes translate as:
上述警告和通知代码翻译为:
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
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
Based on this output I draw the following conclusions:
基于此,我得出以下结论:
- use a newer version of PHP when possible (duh)
- 尽可能使用更新的PHP版本(duh)
- for large arrays the options are limited to:
- either option 5.
$x = end($array); reset($array);
- 要么选择5。$ x =结束(数组);重置(数组);
- or option 7.
$x = $array[count($array)-1];
- 或选择7。$ x = $数组(count($数组)1);
- or option 9.
$x = $array[] = array_pop($array);
- 或选择9。$x = $array[] = array_pop($array);
- either option 5.
- 对于大型数组,选项被限制为:选项5。$ x =结束(数组);重置(数组);或选择7。$ x = $数组(count($数组)1);或选择9。$x = $array[] = array_pop($array);
- for non-auto-indexed arrays, options 7 and 9 are not an option
- 对于非自动索引的数组,选项7和9不是选项
Personally I do not like concerning myself with array internal pointers and prefer a solution in a single expression. Therefore short story I would myself use:
就我个人而言,我不喜欢使用数组内部指针,而喜欢使用单个表达式中的解决方案。因此,我要用我自己的短篇故事:
- for auto-indexed arrays:
- either option 7.
$x = $array[count($array)-1];
- 要么选择7。$ x = $数组(count($数组)1);
- or option 9.
$x = $array[] = array_pop($array);
- 或选择9。$x = $array[] = array_pop($array);
- either option 7.
- 对于自动索引数组:任意选项7。$ x = $数组(count($数组)1);或选择9。$x = $array[] = array_pop($array);
-
for non-auto-indexed arrays:(invalid)-
option 9.$x = $array[] = array_pop($array);
- 选择9。$x = $array[] = array_pop($array);
-
- 对于非自动索引的数组:(无效)选项9。$x = $array[] = array_pop($array);
A bit depending on whether using the array as stack or as queue you can make variations on option 9.
这取决于是否使用数组作为堆栈或作为队列,您可以对选项9进行更改。
#4
32
What's wrong with array_slice($array, -1)
? (See Manual: http://us1.php.net/array_slice)
array_slice($array, -1)有什么问题?(见手册:http://us1.php.net/array_slice)
array_slice()
returns an array. Probably not what you are looking for. You want the element.
array_slice()返回一个数组。可能不是你想要的。你想要的元素。
#5
18
One way to avoid pass-by-reference errors (eg. "end(array_values($foo))") is to use call_user_func or call_user_func_array:
避免引用传递错误的一种方法。“结束(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))));
#6
10
untested: wouldn't this work?
未经考验的:不是这个工作?
<?php
$last_element=end(array_values($array));
?>
Since the array returned by array_values is fleeting, no-one cares if it's pointer is reset.
由于array_values返回的数组是转瞬即逝的,所以没有人关心它的指针是否被重置。
and if you need the key to go with it I guess you'd do:
如果你需要钥匙,我猜你会这么做:
<?php
$last_key=end(array_keys($array));
?>
#7
8
I need this quite often to deal with stacks, and i always find myself baffled that there's no native function that does it without manipulating the array or its internal pointer in some form.
我经常需要它来处理堆栈,我总是发现如果不以某种形式操作数组或它的内部指针,就没有本地函数来处理堆栈,这让我很困惑。
So i usually carry around a util function that's also safe to use on associative arrays.
所以我通常携带一个util函数它在关联数组中也是安全的。
function array_last($array) {
if (count($array) < 1)
return null;
$keys = array_keys($array);
return $array[$keys[sizeof($keys) - 1]];
}
#8
6
end() will provide the last element of an array
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
#9
5
If you don't care about modifying the internal pointer (supports both indexed and associative arrays):
如果您不关心修改内部指针(支持索引数组和关联数组):
// false if empty array
$last = end($array);
// null if empty array
$last = !empty($array) ? end($array) : null;
If you want a utility function that doesn't modify the internal pointer:
如果你想要一个不修改内部指针的效用函数:
function array_last($array) {
if (empty($array)) {
return null;
}
return end($value);
}
The original array's internal pointer is not modified, because the array is copied.
原始数组的内部指针没有被修改,因为数组被复制了。
Thus, the following alternative is actually faster as it doesn't copy the array, it just makes a slice:
因此,下面的选择实际上更快,因为它不复制数组,它只做一个切片:
function array_last($array) {
if (empty($array)) {
return null;
}
foreach (array_slice($array, -1) as $value) {
return $value;
}
}
This "foreach / return" is a tweak for efficiently getting the first (and here single) item.
这个“foreach / return”是有效获取第一个(这里是单个)条目的一个调整。
Finally, the fastest alternative but for indexed arrays only:
最后,除了索引数组之外,最快的选择是:
$last = !empty($array) ? $array[count($array)-1] : null;
#10
5
To get the last element of an array, use:
要获取数组的最后一个元素,请使用:
$lastElement = array_slice($array, -1)[0];
Benchmark
基准
I iterated 1,000 times, grabbing the last element of small and large arrays that contained 100 and 50,000 elements, respectively.
我迭代了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...
I used PHP Version 5.5.32.
我使用的是PHP 5.5.32。
#11
3
For me:
对我来说:
$last = $array[count($array) - 1];
With associatives:
associatives:
$last =array_values($array)[count($array - 1)]
#12
2
To do this and avoid the E_STRICT and not mess with the array's internal pointer you can use:
要做到这一点,并避免E_STRICT和不要打乱数组的内部指针,您可以使用:
function lelement($array) {return end($array);}
$last_element = lelement($array);
lelement only works with a copy so it doesn't affect the array's pointer.
lelement只对复制起作用,因此不会影响数组的指针。
#13
2
Another solution:
另一个解决方案:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
$lastItem = $array[(array_keys($array)[(count($array)-1)])];
echo $lastItem;
#14
1
$lastValue = end(array_values($array))
No modification is made to $array pointers. This avoids the
没有对$array指针进行修改。这样就避免了
reset($array)
which might not be desired in certain conditions.
这在某些情况下是不可取的。
#15
1
For getting the last value from Array :
从数组中获取最后一个值:
array_slice($arr,-1,1) ;
For Removing last value form array :
用于删除最后一个值表单数组:
array_slice($arr,0,count($arr)-1) ;
#16
1
Simply: $last_element = end((array_values($array)))
简单:$ last_element =结束(元素(数组)美元))
Doesn't reset the array and doesn't gives STRICT warnings.
不会重置数组,也不会发出严格的警告。
PS. Since the most voted answer still hasn't the double parenthesis, I submitted this answer.
因为大多数投票的答案仍然没有双括号,所以我提交了这个答案。
#17
1
One more possible solution...
一个可能的解决方案……
$last_element = array_reverse( $array )[0];
#18
1
How about:
如何:
current(array_slice($array, -1))
- works for associative arrays
- 适用于关联数组
- works when
$array == []
(returnsfalse
) - 当$array ==[]时工作(返回false)
- doesn't affect the original array
- 不会影响原始数组。
#19
1
I think this is a slight improvement on all the existing answers:
我认为这是对现有答案的一个小小的改进:
$lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;
- Performs better than
end()
or solutions usingarray_keys()
, especially with large arrays - 使用array_keys()比end()或解决方案执行得更好,特别是对于大型数组
- Won't modify the array's internal pointer
- 不会修改数组的内部指针
- Won't try to access an undefined offset for empty arrays
- 不会尝试访问空数组的未定义偏移量
- Will work as expected for empty arrays, indexed arrays, mixed arrays, and associative arrays
- 对于空数组、索引数组、混合数组和关联数组,是否可以正常工作?
#20
0
What if you want to get the last element of array inside of the loop of it's array?
如果你想在数组的循环中得到数组的最后一个元素呢?
The code below will result into an infinite loop:
下面的代码将导致一个无限循环:
foreach ($array as $item) {
$last_element = end($array);
reset($array);
if ($last_element == $item) {
// something useful here
}
}
The solution is obviously simple for non associative arrays:
对于非关联数组,解决方案显然很简单:
$last_element = $array[sizeof ($array) - 1];
foreach ($array as $key => $item) {
if ($last_element == $item) {
// something useful here
}
}
#21
0
$file_name_dm = $_FILES["video"]["name"];
$ext_thumb = extension($file_name_dm);
echo extension($file_name_dm);
function extension($str){
$str=implode("",explode("\\",$str));
$str=explode(".",$str);
$str=strtolower(end($str));
return $str;
}
#22
-3
In almost every language with arrays you can't really go wrong with A[A.size-1]. I can't think of an example of a language with 1 based arrays (as opposed to zero based).
在几乎每一种使用数组的语言中,您都不能真正出错[A.size-1]。我想不出一种基于数组(而不是基于0)的语言的例子。