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

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -