Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Merge/Replace

Tags:

arrays

php

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";
like image 302
jmccartie Avatar asked May 15 '09 00:05

jmccartie


People also ask

How do I merge two arrays together?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How do you merge elements in an array?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

Does array merge remove duplicates PHP?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

What is difference between Array_combine and Array_merge?

1. array_combine(): It is used to creates a new array by using the key of one array as keys and using the value of another array as values. 2. array_merge(): It merges one or more than one array such that the value of one array appended at the end of the first array.


1 Answers

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

like image 69
Chad Birch Avatar answered Nov 10 '22 22:11

Chad Birch