dannymo
dannymo

Reputation: 408

PHP array empty after pushing in foreach

I am pushing values inside an array in foreach loop and the values seem to be added in the array so the problem is not in the pushing condition. However when I go through that array again, it is empty.

Can please anyone explain to me, why this code

foreach ($allItems as $pair) {
    for ($i = 0; $i < count($keywords); $i++) {
        if ($this->itemInArray($pair["item"], $items2D[$i])) {
            array_push($pair["keywords"], $keywords[$i]->getWord());
        }
    }
    $this->log("Keywords count inside loop: ".count($pair["keywords"]));
}

foreach ($allItems as $pair) {
    $this->log("Keywords count outside loop: ".count($pair["keywords"]));
}

Outputs this:

Keywords count inside loop: 3
Keywords count inside loop: 1
Keywords count inside loop: 1
Keywords count inside loop: 1
Keywords count outside loop: 0
Keywords count outside loop: 0
Keywords count outside loop: 0
Keywords count outside loop: 0

what am I doing wrong and how to fix it?

Upvotes: 1

Views: 1620

Answers (2)

Buck Mathers
Buck Mathers

Reputation: 1

You can not iterate through an array with foreach() while pushing items in to it.

Try pushing to a new variable in the foreach statement:

array_push($newPair,$keywords[$i]->getWord());

Upvotes: 0

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18845

By this you get a copy of the array and modify the copy ($pair):

foreach ($allItems as $pair) {

You need to modify to get reference to $pair (note the &):

foreach ($allItems as &$pair) {

Upvotes: 4

Related Questions