scrub_lord
scrub_lord

Reputation: 119

Nested foreach loops, PHP, how do I manipulate the values?

foreach ($bing_array as $bing_array_val)
{       
    foreach ($final_array as $final_array_val)
    {
        if ($final_array_val["link"] == $bing_array_val["link"])
        {

            $final_array_val["rank"] += $bing_array_val["rank"];
        }
    }
}

The above code has two foreach loops, which are nested.

It should test every bing_array["link"] against every final_array["link"] and if they are the same, the final_array["rank"] value should be += bing_array["rank"] but when I echo final_array, the ["rank"] values are unchanged.

I assume this is a syntax problem, where am I going wrong?

Thanks

Upvotes: 0

Views: 1110

Answers (2)

Dany Caissy
Dany Caissy

Reputation: 3206

Here is the actual code you need :

foreach ($bing_array as &$bing_array_val)
{       
    foreach ($final_array as &$final_array_val)
    {
        if ($final_array_val["link"] == $bing_array_val["link"])
        {
            $final_array_val["rank"] += $bing_array_val["rank"];
        }
    }
    unset(&$final_array_val);
}
unset(&$bing_array_val);

In your initial code, each time you were looping on $final_array, it was creating a temporary value called $final_array_val containing the content. Then, you modified it, and then it was replaced for each occurence of the foreach.

By passing the variables by reference, instead of creating a new temporary variable in the foreach, you use the actual variable which will keep the modifications you have done to it.

Upvotes: 1

paddy
paddy

Reputation: 63481

You need to use the reference syntax (& prefix):

foreach ($final_array as &$final_array_val)
{
}
unset($final_array_val);

Note that the unset is required to break the reference to the last value. Read more here.

Upvotes: 1

Related Questions