note 60746 deleted from function.count by betz
| From: | betz@php.net | Date: | Sun, 15 Jan 2006 21:53:52 +0000 |
| Subject: | note 60746 deleted from function.count by betz | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-101872@lists.php.net to get a copy of this message | ||
Note Submitter: NOjonSPAM at freilich dot com
Reason: useless
----
Using count() in a loop that alters the array, with unset() for example, will produce unexpected
results. This function, part of a log cleaning routine, will fail at the halfway point because each
time through the loop the value of count($logText) has been decreased by one:
<?php
for ($n = 0; $n < count($logText); $n++) {
if ($logText[$n] == "\n") {
unset($logText[$n]);
}
}
?>
The proper way is to define a variable before the loop:
<?php
$count = count($logText);
for ($n = 0; $n < $count; $n++) {
if ($logText[$n] == "\n") {
unset($logText[$n]);
}
}
?>