dplo59755 2013-03-13 21:18
浏览 27
已采纳

从php中删除数组中的元素[重复]

This question already has an answer here:

I have an array that looks like this

 $hours_worked = array('23',0,'24',0)

What want to do is to loop through the array and remove the element that contains 0

What I have so far is:

for($i = 0; $i < count($hours_worked); $i++) 
{
   if($hours_worked[$i] === 0 )
   {
       unset($hours_worked[$i]);
   }    
}

However the result I get is $hours_worked = array(23,24,0). I.e. it does not remove the final element from the array. Any ideas?

</div>
  • 写回答

2条回答 默认 最新

  • doulianglou0898 2013-03-13 21:26
    关注

    The problem with this code is that you are calculating count($hours_worked) on each iteration; once you remove an item the count will decrease, which means that for each item removed the loop will terminate before seeing one item at the end of the array. So an immediate way to fix it would be to pull the count out of the loop:

    $count = count($hours_worked);
    for($i = 0; $i < $count; $i++) {
       // ...
    }
    

    That said, the code can be further improved. For one you should always use foreach instead of for -- this makes the code work on all arrays instead of just numerically indexed ones, and is also immune to counting problems:

    foreach ($hours_worked as $key => $value) {
        if ($value === 0) unset($hours_worked[$key]);
    }
    

    You might also want to use array_diff for this kind of work because it's an easy one-liner:

    $hours_worked = array('23',0,'24',0);
    $hours_worked = array_diff($hours_worked, array(0)); // removes the zeroes
    

    If you choose to do this, be aware of how array_diff compares items:

    Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥15 隐藏系统界面pdf的打印、下载按钮