Tutorial :Array Merge/Replace



Question:

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";  


Solution:1

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".


Solution:2

It's that simple:

$new_array = array_replace(array_1,array_2);

the php manual page


Solution:3

Can't it just be this simple:

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

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


Solution:4

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.


Solution:5

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

foreach ($array2 as $i => $value) {    $array1[$i] = $value;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »