Re: Problem iterating over an array with foreach and a reference variable

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Chris Mika wrote:
> I don't know if I'm doing something wrong or if this is a bug.

the problem is due ot reuse of the variable you define by reference in the
second loop - cant really explain why its doing what you see but IIRC its
not a bug, an artifact of the way references work. someone with a clearer head
and a better understanding might be able to explain the instrincasies of what your seeing.

see what happens if you add the unset() as given below (you will see
that the code does what you expect with the unset()

> 
> Very simply: I created an array with values 1-5. I use a foreach loop to
> iterate over it to add 1 to the values. It correctly iterates over the
> array except for the last value.
> 
> Code:
> <?php
> 
> $test = array(1, 2, 3, 4, 5);
> 
> print "original: <br>";
> foreach ($test as $part) {
>   print "($part) ";
> }
> print "<br> changing: <br>";
> 
> foreach ($test as &$part) {
>   print "($part -> ";
>   $part ++;
>   print "$part) ";
> }

unset($part);

> 
> print "<br>final:<br>";
> foreach ($test as $part) {
>   print "($part) ";
> }
> 
> print "<br>var dump:<br>";
> var_dump($test);
> 
> ?>
> 
> Expected Output:
> original:
> (1) (2) (3) (4) (5)
> changing:
> (1 -> 2) (2 -> 3) (3 -> 4) (4 -> 5) (5 -> 6)
> final:
> (2) (3) (4) (5) (6)
> var dump:
> array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=>
> int(5) }
> 
> Actual Output:
> original:
> (1) (2) (3) (4) (5)
> changing:
> (1 -> 2) (2 -> 3) (3 -> 4) (4 -> 5) (5 -> 6)
> final:
> (2) (3) (4) (5) (5)
> var dump:
> array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> ?(5) }
> 
> Any help?
> 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux