tags:

views:

64

answers:

5

Im curious to know if php has a function that allows me to connect 2 arrays together and replace values from array1 with values of array2 if the values from array2 already exist. see example

array1('value1','value2','value3',); array2('value4','value2','value1');

array3 = functionEmerge(array1, array2);

array3('value1','value2','value3','value4',);

+2  A: 

You could call array_unique() on the result of array_merge() to get your desired result.

Amber
Honestly, I'd suggest jboxer's solution over this - I wasn't actually aware that `+` for arrays functioned as union.
Amber
Yeah, non-numeric keys do complicate things, but if you're using normal arrays like in numerical25's example, I think the union operator (+) is better; much more readable, if nothing else.
jboxer
A: 

the function you're looking for is called array_merge

array array_merge ( array $array1 [, array $array2 [, array $... ]] )

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

arclight
+2  A: 

I believe you are talking about taking the union of two arrays. If that's the case, PHP comes with the union array operator, which is just +. So:

$arr = array('value1', 'value2', 'value3') + array('value1', 'value2', 'value4');

Should get you:

array('value1', 'value2', 'value3', 'value4')

I could be wrong, so test this before you use it.

jboxer
This is wrong. + operator on arrays only merge keys, not values.
yuku
Um, yuku, I tested it and it appears to merge on values if the keys are numeric.
Amber
A: 

I didn't find a single operator for that, but this will work:

$array3 = array_keys(array_flip($array1) + array_flip($array2))
yuku
A: 
Set::merge( $a, $b )
Abba Bryant