echo $b2; ?>
points to post below me.
When you're doing the references with loops, you need to unset($var).
for example
<?php
foreach($var as &$value)
{
...
}
unset($value);
?>
Watch out for this:
foreach ($somearray as &$i) {
// update some $i...
}
...
foreach ($somearray as $i) {
// last element of $somearray is mysteriously overwritten!
}
Problem is $i contians reference to last element of $somearray after the first foreach, and the second foreach happily assigns to it!
Solution to post "php at hood dot id dot au 04-Mar-2007 10:56":
<?php
$a1 = array('a'=>'a');
$a2 = array('a'=>'b');
foreach ($a1 as $k=>&$v)
$v = 'x';
echo $a1['a']; unset($GLOBALS['v']);
foreach ($a2 as $k=>$v)
{}
echo $a1['a']; ?>
Something that might not be obvious on the first look:
If you want to cycle through an array with references, you must not use a simple value assigning foreach control structure. You have to use an extended key-value assigning foreach or a for control structure.
A simple value assigning foreach control structure produces a copy of an object or value. The following code
$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $v)
{
$v1++;
echo $v."n";
}
yields
0
1
which means $v in foreach is not a reference to $v1 but a copy of the object the actual element in the array was referencing to.
The codes
$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $k=>$v)
{
$v1++;
echo $arrV[$k]."n";
}
and
$v1=0;
$arrV=array(&$v1,&$v1);
$c=count($arrV);
9/11 首页 上一页 7 8 9 10 11 下一页 尾页 |