1

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?

2 Answers 2

4

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) {
Sign up to request clarification or add additional context in comments.

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.