RE: foreach weirdness

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

 



> See this following example that illustrates the problem:
> $array = array(0, 1, 2, 3, 4, 5, 6);
> foreach ($array as $index=>$value) { 
> 	if ( ($index+1) < count($array) ) { 
> 		$array[$index+1] += $value; 
> 	} 
> 	echo $value." ";
> }
> echo "<br />";
> foreach ($array as $index=>$value) { 
> 	echo $value." ";
> }
> 
> You'd expect the output to be: 
> 0 1 3 6 10 15 21
> 0 1 3 6 10 15 21
> 
> But it's actually: 
> 0 1 2 3 4 5 6
> 0 1 3 5 7 9 11

Hey,

the ouput you get is right. If you want your ouput you have to rewrite your code.
Currently you are adding the value of the current index to the next indexes value (e.g. $array[0] + $array[1]; $array[1] + $array[2]; etc.).
As I understand it you want to add the current value with the next index (e.g. $array[0] + 1; $array[1] + 2; $array[2] + 3).
--

Hi Stephan, the first foreach loop adds the next value to the current value, not the next index. The reason you don't get the expected result in the first foreach loop is because you need to assign the $value by reference, as per the php manual
foreach ($array as $index=>&$value) 

But then to get the correct output from the second simple foreach loop, you also have to assign the $value by reference, contrary to the php manual. If you don't you get the wrong result and the array becomes corrupted. That could be classified as a bug, or at least the manual needs to elaborate on using a foreach when you assign the $value by reference.

Cheers
Arno


-- 
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