I have two arrays like this:
array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
array(
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
I want to combine these two array such that it does not contains duplicate and as well as keep their original keys. For example output should be:
array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
I have tried this but it is changing their original keys:
$output = array_unique( array_merge( $array1 , $array2 ) );
Any solution?
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.
In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.
concat(array1, array2) to merge 2 or more arrays. These approaches are immutable because the merge result is stored in a new array. If you'd like to perform a mutable merge, i.e. merge into an array without creating a new one, then you can use array1.
Just use:
$output = array_merge($array1, $array2);
That should solve it. Because you use string keys if one key occurs more than one time (like '44'
in your example) one key will overwrite preceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.
Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...
A workaround is to recreate the keys.
$output = array_combine($output, $output);
Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)
$output = $array1 + $array2;
All of this can be seen in: http://php.net/manual/en/function.array-merge.php
You should take to consideration that $array1 + $array2 != $array2 + $array1
$array1 = array(
'11' => 'x1',
'22' => 'x1'
);
$array2 = array(
'22' => 'x2',
'33' => 'x2'
);
with $array1 + $array2
$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
and with $array2 + $array1
$array2 + $array1 = array(
'11' => 'x1',
'22' => 'x2',
'33' => 'x2'
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With