Showing posts with label Iteration. Show all posts
Showing posts with label Iteration. Show all posts

Sunday, September 16, 2007

Iterate over array

Perhaps it sounds repeated to the for - while post, but now instead of executing a code N times, I want to run all the positions of an array. Which is the most advisable way?
In the first place, we have the optimized for.
On the other hand, we can use foreach, that exactly crosses the array of data.
A last alternative is to be crossing the array using its internal pointer.

In this case, the best alternative is foreach, specially dedicated for this.

View example

Saturday, September 8, 2007

for - while

Usually, to iterate a code N times you do

for ($a = 0; $a < N; $a++) {

but, thinking a bit, this code can be optimized, because the second and third sentence can be joined, so we get this

for ($a = -1; ++$a < N;) {

Also, you can think it in this way

$a = 0;
while (++$a < N) {

but the previous approach seems (a bit) better, in the practice. This optimization can improve not much your code, we have to keep in mind this is one of the most common iterations, and you can repeat it a lot along your work.

View example