tags:

views:

344

answers:

5

I have two arrays:

Array
(
    [2005] => 0
    [2006] => 0
    [2007] => 0
    [2008] => 0
    [2009] => 0
)

Array
(
    [2007] => 5
    [2008] => 6.05
    [2009] => 7
)

I want to merge these two arrays such that if a value exists in the 2nd array, it overwrites the first array's value. So the resulting array would be:

Array
(
    [2005] => 0
    [2006] => 0
    [2007] => 5
    [2008] => 6.05
    [2009] => 7
)

Thanks for your help.

UPDATE: This was my best attempt, but it's wildly unsuccessful:

 $final = '';
 foreach ($years as $k => $v){
  if (in_array($k,$values)){
   $final .= $values[$k] . '|';
  }else{
   $final .= $k[$v] . '|';
  }

 }

 echo "final = $final";
A: 

this has already been answered here: http://stackoverflow.com/questions/25147/how-can-i-merge-php-arrays

Josh Curren
On the contrary, that question assumes that you want to merge on the ID. I want to replace if the value does not exist (similar keys in both arrays)
jmccartie
oh. sorry. I do believe there is one that does this already though.
Josh Curren
+1  A: 

I'm not that familiar with PHP, but something like:

foreach ($array2 as $i => $value) {
  $array1[$i] = $value;
}
Brian Duff
I'm guessing I missed a complexity that you may not have explained in detail in the question.
Brian Duff
+1 - this is definitely the simplest and easiest way to do it
nickf
+3  A: 

Well, array merge wont work because it has numeric keys, we should build a new function for this..

function combine($a1, $a2)
    foreach ($a2 as $k => $v) {
        $a1[$k] = $v;
    }
    return $a1;
}

There you go.

José Leal
i'm assuming you mean "foreach"? thanks, jose.
jmccartie
Oh, sorry.. will fix now.
José Leal
Though this function isn't even necessary (there's a built-in operator that does this), the whole function could have been written much more concisely as (sorry, can't linebreak): foreach ($a2 as $k => $v) $a1[$k] = $v; return $a1;
Chad Birch
You are right, since php dont pass references, only values.
José Leal
José Leal
Hi! Thanks for this, it saved my ass :)
Industrial
+11  A: 

As I've just recently learned, PHP has an array union operator that does exactly this:

$result = $a + $b;

Where $a is the array with the values that you want to take precedence. (So in your example, that means that the second array is "$a".

Chad Birch
A: 

Can't it just be this simple:

$new_array = array_unique(array_merge($ar1,$ar2));

Maybe I'm missing something or I'm crazy.

KyleFarris