I am new to PHP and I am experimenting
right now with some foreach loops in PHP.
I know that it is recommended to unset
the foreach loop variables after the loop.
I noticed that if I include the lines // 1 // and
// 2 //, this script prints the right thing.
...
Name: Rachel, Age: 56
Name: Grace, Age: 44
( It also prints the right thing if in the last loop, I use other
variable names like $n and $a instead of $name and $age.)
But if I comment lines // 1 // and // 2 // out, it prints:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34
Name: Lisa, Age: 38
Name: Jack, Age: 26
Name: Ryan, Age: 45
Name: Rachel, Age: 56
Name: Grace, Age: 56
Notice that 56 is printed two times.
Why does it behave that way?
I mean: what happens under the hood?
<?php
$employee_age = array();
$employee_age["Lisa"] = "28";
$employee_age["Jack"] = "16";
$employee_age["Ryan"] = "35";
$employee_age["Rachel"] = "46";
$employee_age["Grace"] = "34";
foreach( $employee_age as $name => $age){
echo "Name: $name, Age: $age <br />";
}
echo "<br>";
unset($age);
unset($name);
foreach( $employee_age as $name => &$age){
$age += 10;
}
// echo "<br>";
// unset($age); // 1 //
// unset($name); // 2 //
foreach( $employee_age as $name => $age){
echo "Name: $name, Age: $age <br />";
}
echo "<br>";
unset($age);
unset($name);
?>