Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add values to an array inside a foreach loop

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 expected 10 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.

like image 308
zessx Avatar asked Jan 29 '15 14:01

zessx


3 Answers

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?

like image 66
Lars Ebert Avatar answered Oct 28 '22 20:10

Lars Ebert


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;
}
like image 5
Radiumrasheed Avatar answered Oct 28 '22 21:10

Radiumrasheed


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

like image 2
Parag Tyagi Avatar answered Oct 28 '22 22:10

Parag Tyagi