RE: [PHP] foreach weirdness
| From: | Arno Kuhl | Date: | Sun, 25 Mar 2012 13:59:58 +0000 |
| Subject: | RE: [PHP] foreach weirdness | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-317257@lists.php.net to get a copy of this message | ||
> 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