I’ve been studying some test questions. One of the questions about array iteration. Here it is :
What is the best way to iterate through the $myarray array, assuming
you want to modify the value of each element as you do?<?php $myarray = array ("My String", "Another String", "Hi, Mom!"); ?>A. Using a for loop
B. Using a foreach loop
C. Using a while loop
D. Using a do…while loop
E. There is no way to accomplish this goals
My answer is “of course foreach loop”. But according to the answer sheet :
Normally, the foreach statement is the most appropriate construct for
iterating through an array. However, because we are being asked to
modify each element in the array, this option is not available, since
foreach works on a copy of the array and would therefore result in
added overhead. Although a while loop or a do…while loop might work,
because the array is sequentially indexed a for statement is best
suited for the task, making Answer A correct.
I still think foreach is the best. And as long as I use it with key I can modify values.
<?php
foreach($myarray as $k=>$v){
$myarray[$k] = "Modified ".$v;
}
?>
Do I miss something?
Nonsense.
If you need proof, you can take the values by reference:
I agree.
No.