Bahadır Birsöz
Bahadır Birsöz

Reputation: 181

Does foreach do its work on a copy of the input array?

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?

Upvotes: 3

Views: 966

Answers (3)

Tessmore
Tessmore

Reputation: 1039

http://php.net/manual/en/function.array-walk.php

array_walk($myarray, "modify");

function modify($value)
{
  $value = "modified " . $value;
}

If you want to apply this to multiple arrays you can even use array_map()

Upvotes: 1

Esailija
Esailija

Reputation: 140230

You could also do

<?php
foreach($myarray as &$v){
    $v = "Modified ".$v;
}
?>

Or in some cases if you have a function that is sufficient for the job:

$myarray = array_map( "trim", $myarray );

It will apply trim function to every element in the array and return the modified version.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

according to the answer sheet:

this option is not available, since foreach works on a copy of the array and would therefore result in added overhead

Nonsense.

If you need proof, you can take the values by reference:

<?php
foreach($myarray as &$v){
    $v = "Modified ".$v;
}
?>

I still think foreach is the best. And as long as i use it with key i can modify values.

I agree.

Do I miss something?

No.

Upvotes: 7

Related Questions