Note the use of references in the foreach loop in PHP

  • 2020-03-31 21:28:47
  • OfStack

 
foreach ($array as &$row) { 
$row = explode('/', $row); 
} 
foreach ($array as $row) { 
//do something 
} 

So let me write it this way, there's a logic error in the second loop, where I add something in the second loop is the output $row, and by the time I get to the last loop the output is the penultimate element, not the last one

To be written
 
foreach ($array as &$row) { 
$row = explode('/', $row); 
} 
unset($row); 
foreach ($array as $row) { 
//do something 
} 

Or let me write the first loop this way
 
foreach ($array as $key => $row) { 
$array[$key] = explode('/', $row); 
} 


Let's talk about the principle
After the first cycle using references, cycle, is $$row references the last element of an array of array, when to start the second loop, $row variable each cycle will be assigned a new value, in PHP, if a memory space is referenced, so as to change it is directly change the value of the memory space, that is, when the second foreach loop for the first time, the last element of $array values were changed to $value of the first element of an array, the second cycle, change the value for the second element, It's going to be changed to the penultimate element on the penultimate loop, and it's going to be the penultimate value on the last loop
Of course, this wouldn't happen if PHP's for loop was scoped...

Related articles: