Hi, Steven G.
I think, I have found out why the code was outputting 'Item1' on each
execution on the second foreach.
Here is what, I did to the code -
<?php
$tags = array(
'Item1',
'Item2'
);
//print_r($tags);
foreach($tags as &$currtag) {
$currtag = array($currtag, 0);
}
unset($currtag); //Unset the value **********
echo "<BR>";
print_r($tags);
echo "<BR>";
//print_r($tags);
foreach($tags as $currtag) {
//print_r($currtag);
print_r($tags);
}
?>
If I am correct then, as per the PHP documentation, reference of a
$value($currtags) and the last array element remain even after the
foreach loop. It is recommended to destroy it by unset().
This can be proved by changing the $currtag variable to something else
in the second foreach loop e.g.
<?php
$tags = array(
'Item1',
'Item2'
);
//print_r($tags);
foreach($tags as &$currtag) {
$currtag = array($currtag, 0);
}
//unset($currtag); //Unset the value **********
echo "<BR>";
print_r($tags);
echo "<BR>";
//print_r($tags);
foreach($tags as $currtag_1) {
//print_r($currtag);
print_r($tags);
}
?>
The second loop was using the previous value of $currtag. I hope this
clears the doubt even though, it does seem odd and a bit illogical at
first.
Cheers,
Mark S.
On Oct 19, 5:00 pm, Steven Gilberd <[EMAIL PROTECTED]> wrote:
> Hi,
>
>
>
> While programming I stumbled across this - can anyone reproduce this, or is
> it just a bug in my system? Replacing the $currtag in the final foreach loop
> with &$currtag causes it to behave as expected, but the code as pasted below
> is obviously badly dysfunctional. Is anyone able to shed some light on this?
>
>
>
> Cheers,
>
> Steve
>
>
>
> -------------------------------------
>
> <?php
>
> $tags = array(
> 'Item1',
> 'Item2'
> );
>
> foreach($tags as &$currtag) {
> $currtag = array($currtag, 0);
>
> }
>
> print_r($tags);
> foreach($tags as $currtag) {
> print_r($tags);
>
> }
>
> ?>
> ----------------------------------
>
>
>
> That code gives the following output:
>
>
>
> Array
> (
> [0] => Array
> (
> [0] => Item1
> [1] => 0
> )
>
> [1] => Array
> (
> [0] => Item2
> [1] => 0
> )
>
> )
> Array
> (
> [0] => Array
> (
> [0] => Item1
> [1] => 0
> )
>
> [1] => Array
> (
> [0] => Item1
> [1] => 0
> )
>
> )
> Array
> (
> [0] => Array
> (
> [0] => Item1
> [1] => 0
> )
>
> [1] => Array
> (
> [0] => Item1
> [1] => 0
> )
>
> )
>
--~--~---------~--~----~------------~-------~--~----~
NZ PHP Users Group: http://groups.google.com/group/nzphpug
To post, send email to [email protected]
To unsubscribe, send email to
[EMAIL PROTECTED]
-~----------~----~----~----~------~----~------~--~---