php - Strange behavior Of foreach -


<?php   $a = array('a', 'b', 'c', 'd');    foreach ($a &$v) { }   foreach ($a $v) { }    print_r($a); ?> 

i think it's normal program output getting:

array (     [0] =>     [1] => b     [2] => c     [3] => c ) 

can please explain me?

this well-documented php behaviour see warning on foreach page of php.net

warning

reference of $value , last array element remain after foreach loop. recommended destroy unset().

$a = array('a', 'b', 'c', 'd');  foreach ($a &$v) { } unset($v); foreach ($a $v) { }  print_r($a); 

edit

attempt @ step-by-step guide happening here

$a = array('a', 'b', 'c', 'd'); foreach ($a &$v) { }   // 1st iteration $v reference $a[0] ('a') foreach ($a &$v) { }   // 2nd iteration $v reference $a[1] ('b') foreach ($a &$v) { }   // 3rd iteration $v reference $a[2] ('c') foreach ($a &$v) { }   // 4th iteration $v reference $a[3] ('d')                            // @ end of foreach loop,                           //    $v still reference $a[3] ('d')  foreach ($a $v) { }    // 1st iteration $v (still reference $a[3])                            //    set value of $a[0] ('a').                           //    because reference $a[3],                            //    sets $a[3] 'a'. foreach ($a $v) { }    // 2nd iteration $v (still reference $a[3])                            //    set value of $a[1] ('b').                           //    because reference $a[3],                            //    sets $a[3] 'b'. foreach ($a $v) { }    // 3rd iteration $v (still reference $a[3])                            //    set value of $a[2] ('c').                           //    because reference $a[3],                            //    sets $a[3] 'c'. foreach ($a $v) { }    // 4th iteration $v (still reference $a[3])                            //    set value of $a[3] ('c' since                            //       last iteration).                           //    because reference $a[3],                            //    sets $a[3] 'c'. 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -