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


i trying add key=>value pair array while using foreach loop, when value added foreach loop needs process new key=>value pair.

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

if print array after loop, expect see 5 kv's, instead see this:

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

is there way, when add fourth pair, process fifth pair gets added within foreach loop (or kind of loop?)

according php documentation,

as foreach relies on internal array pointer changing within loop may lead unexpected behavior.

you cannot modify array during foreach. however, user posted example of regular while loop need: http://www.php.net/manual/en/control-structures.foreach.php#99909

i report 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 output:

1 => a

2 => b

3 => c

4 => d

5 => e


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -