note 60746 added to function.count

From: Date: Sun, 15 Jan 2006 19:46:37 +0000
Subject: note 60746 added to function.count
Groups: php.notes 
Request: Send a blank email to php-notes+get-101863@lists.php.net to get a copy of this message
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]); } } ?> ---- Manual Page -- http://www.php.net/manual/en/function.count.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+60746 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60746&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60746&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60746&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60746&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60746&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60746&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60746&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+60746&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#101863) next »