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 30instead 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.
$aDataand insert the values in there with yourforeachloop.foreachuse aforloop and iterate through the length of the array and using the index variable of the for loop, add whatever you want to your array.