删除最后一个数组值?php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3338413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
deleting last array value ? php
提问by Adam Ramadhan
1 question type
1个问题类型
$transport = array('foot', 'bike', 'car', 'plane');
can i delete the plane ? is there a way ?
我可以删除飞机吗?有办法吗?
2 question type
2 题型
$transport = array('', 'bike', 'car', ''); // delate the last line
$transport = array('', 'bike', 'car', 'ferrari'); // dont the last line
$transport = array('ship', 'bike', 'car', 'ferrari'); // dont the last line
is there a easy way to delete the last array " if last array value is empty then delete " if not empty then don't delete ? but not to delete the first array ?
有没有一种简单的方法可以删除最后一个数组“如果最后一个数组值为空则删除”如果不为空则不要删除?但不是删除第一个数组?
回答by Scott Saunders
if(empty($transport[count($transport)-1])) {
unset($transport[count($transport)-1]);
}
回答by Jim W.
The easiest way: array_pop()which will pop an element of the end of the array.
最简单的方法:array_pop()将弹出数组末尾的元素。
As for the 2nd question:
至于第二个问题:
if (end($transport) == "") {
array_pop($transport);
}
Should handle the second.
应该处理第二个。
EDIT:
编辑:
Modified the code to conform to the updated information. This should work with associative or indexed based arrays.
修改了代码以符合更新的信息。这应该适用于基于关联或索引的数组。
Fixed the array_pop, given Scott's comment. Thanks for catching that!
鉴于 Scott 的评论,修复了 array_pop。谢谢你抓住那个!
Fixed the fatal error, I guess empty cannot be used with end like I had it. The above code will no longer catch null / false if that is needed you can assign a variable from the end function and test that like so:
修复了致命错误,我猜空不能像我一样与 end 一起使用。如果需要,上面的代码将不再捕获 null/false,您可以从 end 函数中分配一个变量并进行测试,如下所示:
$end_item = end($transport);
if (empty($end_item)) {
array_pop($transport);
}
Sorry for posting incorrect code. The above I tested.
抱歉发布了错误的代码。以上是我测试的。
回答by JAL
for # 1,
对于#1,
$transport=array_slice($transport,0,count($transport)-1)
回答by Martin AJ
回答by viji
$endvalue = & end($transport);
array_pop($endvalue);

