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条)

报告相同问题?