When using a foreach loop and a reference, how can I stop the last member pointing to a reference?
Consider this code...
$a = range(1, 5);
foreach($a as &$b) { }
var_dump(开发者_运维问答$a);
The output is...
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
&int(5)
}
CodePad.
See the &
on the last member? How can I stop that?
You can unset($b)
.
$a = range(1, 5);
foreach($a as &$b) { }
unset($b);
var_dump($a);
CodePad.
You should unset()
to avoid this...
$a = range(1, 5);
foreach($a as &$b) { }
$b = 10;
var_dump($a);
...which outputs...
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
&int(10)
}
CodePad.
精彩评论