Fastest way to iterate an array in PHP

Viewed 21585

I'm studying for the Zend PHP certification.

I am not sure about the answer to this question.

Question: What is the best way to iterate and modify every element of an array using PHP 5?

a) You cannot modify an array during iteration

b) for($i = 0; $i < count($array); $i++) { /* ... */ }

c) foreach($array as $key => &$val) { /* ... */ }

d) foreach($array as $key => $val) { /* ... */ }

e) while(list($key, $val) = each($array)) { /* ... */ }


My instinctive is (B) since there is no need to create a temporary variable, but then I realize it won't work for associative arrays.

Further searching around the Internet I found this:

Storing the invariant array count in a separate variable improves performance.

$cnt = count($array);
for ($i = 0; $i < $cnt; $i++) { }
3 Answers
Related