这段代码的问题是你count($hours_worked)
每次迭代都在计算;一旦你删除了一个项目,计数就会减少,这意味着对于每个删除的项目,循环将在看到数组末尾的一个项目之前终止。因此,解决它的直接方法是将计数拉出循环:
$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.