📜 ⬆️ ⬇️

Be careful with the iteration of arrays by reference.

I just stumbled upon a very unpleasant PHP feature when iterating through arrays with reference to elements (the foreach construction with &).

See for yourself:
$test = array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5); print_r($test); foreach ($test as $key => $value) { echo "{$key} => {$value}\n"; } 


We get what we expected:
 Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) 1 => 1 2 => 2 3 => 3 4 => 4 5 => 5 


But it is worth adding an iteration of the link:
 $test = array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5); foreach ($test AS &$value) { // - .        } print_r($test); foreach ($test as $key => $value) { echo "{$key} => {$value}\n"; } 

')
... how we get an unexpected result:
 Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) 1 => 1 2 => 2 3 => 3 4 => 4 5 => <b>4</b> 


I do not fully understand what the joint is, it is somehow related to the fact that in $ value there is a link to the last element after exiting the first cycle. You can avoid this behavior in two ways: Either you need to iterate the second cycle also by reference, or use a different name instead of $ value.

Source: https://habr.com/ru/post/59299/


All Articles