views:

51

answers:

3

Is there a way i can replace the values of one array with the values of another which has identical keys?

$arr1 = Array
        (
            [key1] => var1
            [key2] => var2
        )
$arr2 = Array
        (
            [key1] => var3
            [key2] => var4
        )

I want to change $arr1's values to the ones in $arr2 im doing this about 10 times, and i can do it line by line, but im wondering if there's a simpler way. Thanks!

+2  A: 

Check php's array_merge() function.

$arr1 = array_merge($arr1,$arr2);
Disgone
wont that just create double the keys?EDIT: it worked, thanks!
Diesal11
It depends on what you're using for keys in your array. String keys will take the 2nd's value, numeric keys append.
Disgone
@Diesal11 Nope.
NullUserException
ok thanks! ill click this as the answer in 9 mins when it lets me XD
Diesal11
A: 

You can try this:

$new_array = array_combine($arr1, $arr2);
jeremysawesome
array_merge() as NullUserException posted is probably the better way to go. Either method would work if the keys are the same.
jeremysawesome
Sorry, this is wrong. It would create `array('var1' => 'var3', 'var2' => 'var4')`
Felix Kling
@Felix - Thanks for catching that - I stand corrected. This is definitely the wrong way to do what the OP wants. This is the correct way of doing this with array_combine, `array_combine(array_flip($arr1), $arr2);`
jeremysawesome
+1  A: 

If the keys in array 1 and 2 are identical:

$arr1 = $arr2;

If all keys of array 2 are guaranteed to be in array 1 (array 2 is a subset of array 1):

$arr1 = array_merge($arr1, $arr2);

If some keys of array 2 are not in array 1 and you want only the keys that are in array 1 to be replaced (array 2 is not a subset of array 1, and you only want to merge the intersecting part):

$arr1 = array_merge($arr1, array_intersect_key($arr2, $arr1));
deceze
this way would also work (the first one) but the next step would replace $arr2 with values from $arr3, so i think array_merge would work better
Diesal11
@Diesal If `$arr1 = $arr2` actually works for you, you don't really want to *merge* arrays as much as *replace a variable* wholesale. Maybe with some more code we could recommend a better way to do what you're trying to do.
deceze
well in the end it goes back to rows in MYSQL, im actually replacing the values of one rows columns with the next row. i haven't fully written it up yet. so thats all i can give you atm
Diesal11