Search code examples
phparraysforeachpushis-empty

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?


Solution

  • 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) {