I'm trying to edit an array on the fly, inside a foreach
loop. I basically analyse each key, and if this key match the one I want, I want to add another entry in the array immediately after this one.
If I take this code,
$values = array(
'foo' => 10,
'bar' => 20,
'baz' => 30
);
foreach($values as $key => $value){
print $value . ' ';
if($key == 'bar'){
$values['qux'] = 21;
}
}
I've got 2 problems,
- first, the output is
10 20 30
instead of the expected10 20 30 21
- second, even if I solve the first problem, my value will still be added at the end of my array
How could I add the qux
entry between bar
and baz
ones?
Thanks for your ideas.