1 question type
$transport = array('foot', 'bike', 'car', 'plane');
Run Code Online (Sandbox Code Playgroud)
can i delete the plane ? is there a way ?
2 question type
$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
Run Code Online (Sandbox Code Playgroud)
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 ?
Sco*_*ers 39
if(empty($transport[count($transport)-1])) {
unset($transport[count($transport)-1]);
}
Run Code Online (Sandbox Code Playgroud)
Jim*_* W. 31
最简单的方法:array_pop()将弹出数组末尾的元素.
至于第二个问题:
if (end($transport) == "") {
array_pop($transport);
}Run Code Online (Sandbox Code Playgroud)
应该处理第二个.
编辑:
修改代码以符合更新的信息.这应该适用于基于关联或索引的数组.
修正了array_pop,给出了Scott的评论.谢谢你抓住了!
修复了致命错误,我想空的不能和我一样使用.如果需要,上面的代码将不再捕获null/false,您可以从end函数中分配变量并进行测试,如下所示:
$end_item = end($transport);
if (empty($end_item)) {
array_pop($transport);
}Run Code Online (Sandbox Code Playgroud)
很抱歉发布错误代码.以上我测试过.
JAL*_*JAL 10
对于#1,
$transport=array_slice($transport,0,count($transport)-1)
Run Code Online (Sandbox Code Playgroud)
您可以通过array_pop()功能简单地做到这一点:
array_pop($transport);
Run Code Online (Sandbox Code Playgroud)