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,
10 20 30
instead of the expected 10 20 30 21
How could I add the qux
entry between bar
and baz
ones?
Thanks for your ideas.
Foreach will not loop through new values added to the array while inside the loop.
If you want to add the new value between two existing values, you could use a second array:
$values = array(
'foo' => 10,
'bar' => 20,
'baz' => 30
);
$newValues = array();
foreach($values as $key => $value)
{
$newValues[$key] = $value;
if($key == 'bar')
{
$newValues['qux'] = 21;
}
}
print implode(' ', $newValue);
Also, see one of my favorite questions on StackOverflow discussing the foreach loop: How does PHP 'foreach' actually work?
You can use the ampersand sign before the value.
//populate all the promos into their promoG groups
foreach($unclaimedPromoGroups as &$unclaimedPromoGroup) {
$_promo = new Promo();
$_promo->promoGroupID = $unclaimedPromoGroup['promo_groupID'];
$promo = $_promo->getGroupPromos();
$unclaimedPromoGroup["promos"] = $promo;
}
For this you need to create a new array,
<?php
$values = array(
'foo' => 10,
'bar' => 20,
'baz' => 30
);
$newarray = array();
foreach($values as $k => $v)
{
$newarray[$k] = $v;
if($k == 'bar')
$newarray['qux'] = 21;
}
echo implode(' ', $newarray);
Demo:
http://3v4l.org/N4XgB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With