deleting last array value ? php

Ada*_*han 17 php arrays

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)

  • 很高兴你找到了你需要的东西.只是你理解,如果它是一个空字符串,roddik的代码将删除数组中的最后一个元素.我将删除最后一个元素,如果它是false,null或empty()函数认为为空的任何其他值.可能要么适合你. (3认同)

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)

很抱歉发布错误代码.以上我测试过.

  • array_pop返回数组的最后一个元素.您的示例代码将使用OP不需要的元素覆盖整个数组. (3认同)
  • 使用array_pop更有意义,因为它适用于关联哈希和基于索引的数组. (2认同)

JAL*_*JAL 10

对于#1,

$transport=array_slice($transport,0,count($transport)-1)
Run Code Online (Sandbox Code Playgroud)

  • 不需要获取数组长度:`array_slice($ transport,0,-1)` (2认同)

Mar*_* AJ 6

您可以通过array_pop()功能简单地做到这一点:

array_pop($transport);
Run Code Online (Sandbox Code Playgroud)

  • 对于那些更喜欢 php.net 而不是 w3schools.com 的人 - http://php.net/manual/en/function.array-pop.php (2认同)