note 99280 modified in control-structures.foreach by danbrown
| From: | danbrown@php.net | Date: | Sun, 08 Aug 2010 14:41:13 +0000 |
| Subject: | note 99280 modified in control-structures.foreach by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-171464@lists.php.net to get a copy of this message | ||
Your last value changes after use of references.
<?php
$arr = array(' one ', ' two ', ' tree ', ' four ', '
five ');
print_r($arr);
foreach ($arr as &$str)
$str = trim($str);
print_r($arr);
foreach ($arr as $str)
echo $str . "\n";
print_r($arr);
?>
Array ( Array ( one Array (
[0] => one [0] => one two [0] => one
[1] => two [1] => two tree [1] => two
[2] => tree [2] => tree four [2] => tree
[3] => four [3] => four four [3] => four
[4] => five [4] => five [4] => four
) ) )
<?php
$arr = array(' one ', ' two ', ' tree ', ' four ', '
five ');
foreach ($arr as &$str)
$str = trim($str);
foreach ($arr as $str) {
print_r($arr);
echo $str . "\n";
}
print_r($arr);
?>
[0] => one => one => one => one => one => one
[1] => two => two => two => two => two => two
[2] => tree => tree => tree => tree => tree => tree
[3] => four => four => four => four => four => four
[4] => one => two => tree => four => four => four
tested in PHP 5.2.4 and PHP 5.3.0
--was--
Your last value changes after use of references.
$arr = array(' one ', ' two ', ' tree ', ' four ', '
five ');
print_r($arr);
foreach ($arr as &$str)
$str = trim($str);
print_r($arr);
foreach ($arr as $str)
echo $str . "\n";
print_r($arr);
Array ( Array ( one Array (
[0] => one [0] => one two [0] => one
[1] => two [1] => two tree [1] => two
[2] => tree [2] => tree four [2] => tree
[3] => four [3] => four four [3] => four
[4] => five [4] => five [4] => four
) ) )
$arr = array(' one ', ' two ', ' tree ', ' four ', '
five ');
foreach ($arr as &$str)
$str = trim($str);
foreach ($arr as $str) {
print_r($arr);
echo $str . "\n";
}
print_r($arr);
[0] => one => one => one => one => one => one
[1] => two => two => two => two => two => two
[2] => tree => tree => tree => tree => tree => tree
[3] => four => four => four => four => four => four
[4] => one => two => tree => four => four => four
tested in PHP 5.2.4 and PHP 5.3.0
http://php.net/manual/en/control-structures.foreach.php