从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>

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.

Try foreach loops instead

$new_array = array();
foreach($hours_worked as $hour) {
   if($hour != '0') {
      $new_array[] = $hour;
   }
}
// $new_array should contain array(23, 24)