Combining add and replacing values
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',);
You could call array_unique()
on the result of array_merge()
to get your desired result.
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.
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.
I didn't find a single operator for that, but this will work:
$array3 = array_keys(array_flip($array1) + array_flip($array2))
Set::merge( $a, $b )
精彩评论