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?
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 proceding 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