note 114318 added to control-structures.for
| From: | Warbo | Date: | Thu, 06 Feb 2014 17:37:38 +0000 |
| Subject: | note 114318 added to control-structures.for | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198425@lists.php.net to get a copy of this message | ||
Remember that for-loops don't always need to go 'forwards'. For example, let's
say I have the following code:
<?php
for ($i = 0; $i < calculateLoopLength(); $i++) {
doSomethingWith($i);
}
>?
As other comments have pointed out, if "calculateLoopLength" will keep giving back the
same value, it can be moved outside the loop:
<?php
$loopLength = calculateLoopLength();
for ($i=0; $i < $loopLength; $i++) {
doSomethingWith($i);
}
?>
However, if the order the looping doesn't matter (ie. each iteration is independent) then we
don't need to use an extra variable either, we can just count down (ie. loop
'backwards') instead:
<?php
for ($i=calculateLoopLength(); $i > 0; $i--) {
doSomething($i);
}
?>
In fact, we can simplify this even more, since "$i > 0" is equivalent to "$i"
(due to type casting):
<?php
for ($i=calculateLoopLength(); $i; $i--) {
doSomething($i);
}
?>
Finally, we can switch to a 'pre-decrement' instead of a 'post-decrement' to be
slightly more efficient (see, for example, http://dfox.me/2011/04/php-most-common-mistakes-part-2-using-post-increment-instead-of-pre-increment/
):
<?php
for ($i = calculateLoopLength(); $i; --$i) {
doSomething($i);
}
?>
In this case we could also replace the entire loop with a map, which might make your algorithm
clearer (although this won't work if calculateLoopLength() == 0):
<?php
array_map('doSomething',
range(0, calculateLoopLength() - 1));
?>
----
Server IP: 72.52.91.14
Probable Submitter: 72.52.91.14
----
Manual Page -- http://php.net/manual/en/control-structures.for.php
Edit -- https://master.php.net/note/edit/114318
Del: integrated -- https://master.php.net/note/delete/114318/integrated
Del: useless -- https://master.php.net/note/delete/114318/useless
Del: bad code -- https://master.php.net/note/delete/114318/bad+code
Del: spam -- https://master.php.net/note/delete/114318/spam
Del: non-english -- https://master.php.net/note/delete/114318/non-english
Del: in docs -- https://master.php.net/note/delete/114318/in+docs
Del: other reasons-- https://master.php.net/note/delete/114318
Reject -- https://master.php.net/note/reject/114318
Search -- https://master.php.net/manage/user-notes.php