views:

549

answers:

4

I'm studying for the Zend PHP certification.

Not sure 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 temporary variable then I realize it won't work for associative arrays. Further searching around the net found this: Storing the invariant array count in a separate variable improves performance.

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

SPL would be the best answer here.

David Kuridža
+1, even it is just "the half solution"
daemonfire300
SPL doesn't solve the question. Even if it was available as an answer, we're talking looping, not the Traversable being looped.
Kevin Peno
+3  A: 

You can iterate and modify every element of an array with any of the shown constructs. But some notes on that:

b) Is only useful if the array is a numeric array with the keys from 0 to n-1.

c) Is useful for both kinds of arrays. Additionally $value is a reference of the element’s value. So changing $value inside foreach will also change the original value.

d) Like c) except $value is a copy of the value (note that foreach operates on a copy of $array). But with the key of the element you can access and change the original value with $array[$key].

e) Like d). Use $array[$key] to access and change the original element.

Gumbo
+7  A: 

From these options C would be the obvious answer.

The remaining options (besides A) may be used to achieve that, depending on the code inside the parenthesis, but the question does NOT show that code. So it must be C.

And you are answering the wrong question - yes doing count() before the for cycle will improve performance, but this question is not about performance.

Anti Veeranna
VolkerK
A: 

I'd love to hear what the consensus is. I use c) in a plugin and it seems that some users get a syntax error there, even though they swear that they are on PHP 5. Googling seems to recommend array_walk instead - which is not listed as an option above!

anmari