zessx
zessx

Reputation: 68790

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,

How could I add the qux entry between bar and baz ones?

Thanks for your ideas.

Upvotes: 12

Views: 56189

Answers (4)

Radiumrasheed
Radiumrasheed

Reputation: 103

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;
}

Upvotes: 5

QHip
QHip

Reputation: 11

The solution below uses the same array.

$values = array(
    'foo' => 10,
    'bar' => 20,
    'baz' => 30
);

function match($niddle, $haystack, $push, $offset = 0) {
    foreach(array_slice($haystack, $offset) as $key => $value) 
    {
        print $value . ' ';
        if($key == $niddle) 
        {
            $i = array_search($niddle, array_keys($haystack)) + 1;
            $haystack = array_slice($haystack, 0, $i, true) + $push + array_slice($haystack, $i, count($haystack) - $i, true);
            $haystack = match($niddle, $haystack, $push, $i);
            break;
        }
    }

    return $haystack;
}

$values = match('bar', $values, array('qux'=>21));

var_dump($values);

Upvotes: 1

Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

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?

Upvotes: 20

Parag Tyagi
Parag Tyagi

Reputation: 8960

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

Upvotes: 2

Related Questions