Re: foreach - Array



Carved in mystic runes upon the very living rock, the last words of David
Haynes of comp.lang.php make plain:

iavian wrote:
hi

i want to modify an array in foreach loop

foreach($array as $ele){
$ele = $some_random_string;
}

i should see here the modified $array .

thnaks in advance

foreach( $array as &$ele ) {
$ele = $some_random_string;
}

should work as you want it to.

Only in PHP5.

http://us3.php.net/manual/en/control-structures.foreach.php

"Unless the array is referenced, foreach operates on a copy of the
specified array and not the array itself....As of PHP 5, you can easily
modify array's elements by preceding $value with &. This will assign
reference instead of copying the value."

--
Alan Little
Phorm PHP Form Processor
http://www.phorm.com/
.



Relevant Pages

  • Re: [PHP] foreach() using current() strange beahvior
    ... that's expected as foreach moves the internal array pointer, ... When using the internal pointer just by calling current(so not moving ... Unless the array is referenced, foreach operates on a copy of the ...
    (php.general)
  • Re: a question about for and foreach
    ... foreach (@array) { ... why @array are changed after this foreach loop!!! ... The "foreach" loop iterates over a normal list value and sets the ... If any element of LIST is an lvalue, you can modify it by modifying ...
    (perl.beginners)
  • Re: safe to delete elements of array in foreach
    ... I agree with Jon on this one. ... I make it a habit not to delete entries in a foreach() loop. ... build an array of keys I want to delete, and after the loop ends, delete ... I don't know whether an operation like this is guaranteed to work in PHP ...
    (comp.lang.php)
  • Re: [PHP] Foreach
    ... The problem I am having is getting both to update the table in MySQL. ... echo "$t"; ... foreach { ... // foreach expects an array, ...
    (php.general)
  • Re: safe to delete elements of array in foreach
    ... (normally this is not the case but not sure in php) ... I make it a habit not to delete entries in a foreach() loop. ... build an array of keys I want to delete, and after the loop ends, ...
    (comp.lang.php)