Heya, cheesecaker.
The reason why I am very against using for loops as a method of array traversal in general is because many programmers are tempted to do this:
-
for($i=0; $i<sizeof($array); $i++)
-
This is in fact the most inefficient way to traverse an array:
- sizeof() gets executed at the start of every single iteration, which is a tremendous waste,
- Any PHP guru can tell you that ++$i is faster than $i++, and
- for doesn't handle non-numeric indexes without modification, whereas foreach handles them automatically.
Incidentally, a better way to write the above example would be this:
-
for( $i = 0; isset($array[$i]); ++$i )
-
Note the use of isset(), which does the same thing but is exponentially faster than using count() or sizeof() at every iteration.
However, in your case, if the size of the array is actually constant, your code will work very nicely (with the exception of you'll want to change $i++ to ++$i). I wouldn't worry about changing it to a foreach.
If you find that there is a large number of questions (without testing, I couldn't tell you exactly how many), you may actually find foreach to be more efficient, as then you only have to look up one symbol instead of two:
-
for( $i = 0; isset($array[$i]); ++$i )
-
{
-
echo $array[$i];
-
}
-
In the above loop, PHP evaluates isset($array[$i]) and echo $array[$i], which means it has to resolve $array and $i, and then find the matching index in $array. That's a lot of symbols to look up.
However, when you use a foreach loop:
-
foreach( $array as $element )
-
{
-
echo $element;
-
}
-
PHP internally creates the variable $element and assigns it the value of each element per iteration, so PHP only has to lookup $element once. It's much more efficient.
For small sets of questions and answers, I wouldn't worry about it. For large sets (probably on the scale of >= 50), consider using foreach instead.