note 53952 added to control-structures.foreach
| From: | JaGx at osu1 dot php dot net | Date: | Sat, 18 Jun 2005 03:55:54 +0000 |
| Subject: | note 53952 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-90616@lists.php.net to get a copy of this message | ||
On the note of Paul's for loop:
function foo($x) {
global $arr; // some Array
for($i=0; $i < count($arr); $i++) {
if($arr[$i][0] == $x) {
echo $arr[$i][1]."\n";
foo($arr[$i][0]);
}
}
}
------------
The middle part of the for loop is evaluated every time it loops which means the count function is
called as many times as it loops. It's always better (performance/speed wise) to put the count
as the initialization code:
function foo($x) {
global $arr; // some Array
for($i=count($arr)-1;; $i>=0; $i++) {
if($arr[$i][0] == $x) {
echo $arr[$i][1]."\n";
foo($arr[$i][0]);
}
}
}
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+53952
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53952&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53952&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53952&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53952&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+53952&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53952&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+53952&report=yes
Search -- http://master.php.net/manage/user-notes.php