3

Possible Duplicate:
Strange behavior Of foreach

Why PHP sometimes change last element of array?

I have a array:

Array
(
    [0] => a_
    [1] => b_
    [2] => c_
    [3] => d_
)

When I try print out all emenets. And output is:

a_
b_
c_
c_

Full code is:

<?
$a = array('a', 'b', 'c', 'd');

foreach ($a as &$value)
    $value = "{$value}_";

print_r($a);

foreach ($a as $value) {
    echo "$value\n";
}

Why?

Community
  • 1
  • 1
neworld
  • 7,757
  • 3
  • 39
  • 61

2 Answers2

11

Either using a different variable name in your second loop or unsetting $value after your first one will solve this problem.

$a = array('a', 'b', 'c', 'd');

foreach ($a as &$value) {
    $value = "{$value}_";
}

unset($value);

print_r($a);

foreach ($a as $value) {
    echo "$value\n";
}
FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
Eric_Lord
  • 178
  • 7
1

Looks like php messes up the pointer adress in your example:

Can't you write it like this:

<?php

    $a = array('a', 'b', 'c', 'd');

    for ($i = 0; $i < count($a); $i++)
        $a[$i] = "{$a[$i]}_";

    print_r($a);

    foreach ($a as $value) {
        echo "$value\n";
    }

?>
Andreas Helgegren
  • 1,640
  • 12
  • 11