Access to newly added key => value in associative array during loop

I am trying to add a key => value pair to an array when using the foreach loop, when this value is added, the foreach loop should process the new key pair =>.

$array = array( 'one' => 1, 'two' => 2, 'three' => 3 ); foreach($array as $key => $value) { if ($key == 'three') { $array['four'] = 4; } else if ($key == 'four') { $array['five'] = 5; } } 

If I print an array after the loop, I would expect to see all 5 squares, but instead I only see this:

 Array ( [one] => 1 [two] => 2 [three] => 3 [four] => 4 ) 

Is there some way when I add a fourth pair to actually process it so that the fifth pair is added to this foreach loop (or another type of loop?)

+4
source share
2 answers

According to php documentation,

Since foreach relies on a pointer to an internal array, changing it in a loop can lead to unexpected behavior.

You cannot modify an array during foreach. However, the user posted an example of a regular while loop that does what you need: http://www.php.net/manual/en/control-structures.foreach.php#99909

I report it here

 <?php $values = array(1 => 'a', 2 => 'b', 3 => 'c'); while (list($key, $value) = each($values)) { echo "$key => $value \r\n"; if ($key == 3) { $values[4] = 'd'; } if ($key == 4) { $values[5] = 'e'; } } ?> 

the code above is displayed:

1 => a

2 => b

3 => c

4 => d

5 => e

+4
source

This is because PHP will internally use its own copy of the array pointer. You are not hieroglyphizing its original key / values โ€‹โ€‹not through a modified array.

Since the original array contains the key three , the first if statement will match, but not the second

Another simpler example is the fact that this is not an infinite loop:

 $array = array(1); foreach($array as $val) { $array []= $val +1; } var_dump($array); 

Output:

 array(2) { [0] => int(1) [1] => int(2) } 

However , the PHP documentation says not so much:

Because foreach relies on a pointer to an internal array that changes it in a loop, it can lead to unexpected behavior.

+2
source

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


All Articles