#PHP: using for
instead of foreach
If you use PHPMD, you'll probably have already found the Avoid unused local variables such as $foo
message at your foreach loops, where $foo
represents the index for each value in your loop, as below:
foreach ($values as $foo => $bar) {
// stuffs
}
We usually apply foreach() because it manipulates the value itself inside the variable being submited in the loop (so, as the example above, we can iterate and change values inside $values
with one stone), which is handy in so many times.
However, sometimes the index variable is not even being used by no parts of your code. This results in some more memory consumption (well this is a variable so you are locating memory for it && last but not least foreach is well known by leaving variables in your memory without cleaning them when the loop is finished so in the end you find yourself consuming more memory than you need), and, for the Mess Detector buddy mentioned above, it starts to raise a few alerts until you remove this little fella from your code.
So how to substitute foreach in those cases?
<continues, check http://stackoverflow.com/questions/13098058/replace-foreach-with-for-iteration-in-php and http://php.net/manual/en/control-structures.alternative-syntax.php>