Hi,

> <?php
> $a = array(1,2,3);
> #$r =& $a;
> echo "current before foreach: " . current($a) . "<br>\n";
> foreach($a as $b) {
>      echo "- value in cycle: " . $b . "<br>\n";
>      echo "-- current in cycle: " . current($a) . "<br>\n";
> }
> echo "current before foreach: " . current($a) . "<br>\n";
> ?>
> 
> Try it, and the delete the hash mark and try again.

I tried to answer this question in the bug report page.

>>>> To say more precisely, foreach statement always makes use of a copy of
>>>> the given array instead of the original itself unless the array is a
>>>> reference or has a reference.

What I meant by this is

1) Each time before entering a foreach loop, php first tries to make a copy of
   the array being iterated.

2) In case the array variable is either referenceing another variable or
   referenced by another variable, no copy is made here and the original
   array is used instead. Because of this behaviour, the original's internal
   array pointer increases in the loop eventually.

And once a variable is referenced by another, both are treated as "reference"
from then on. For example,

<?php
  $test = array();
  $test['a'] = 'a';
  $test['b'] = &$test['a'];

  debug_zval_dump($test);
?>

This script produces following output:

array(2) refcount(2){
  ["a"]=>
  &string(1) "a" refcount(2)
  ["b"]=>
  &string(1) "a" refcount(2)
}

Moriyoshi


-- 
PHP Development Mailing List <http://www.php.net/>
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to