Quick question - merging two or more arrays without reindexing |
[eluser]TheFuzzy0ne[/eluser]
Hi everyone. I need to merge two arrays together without the keys being reindexed. I know this can be done, but I cannot for the life of me remember how to go about doing it without looping through the array(s) to be added and adding them one by one. Please could someone tell me the correct function to use? Many thanks in advance.
[eluser]Dam1an[/eluser]
I'm still half asleep, so might understand this wrong Is what you're trying to acheive is merge 1,3,4,6,8,9 and 1,4,5,6 into 1,1,3,4,4,5,6,6,8,9?
[eluser]TheFuzzy0ne[/eluser]
OK, an example: Code: $arr1 = array( When there are merged together, I should have an array like this: Code: $arr1 = array( But instead, I get an array like this: Code: $arr1 = array( Note: The keys have been reindexed. I'm trying to merge the two together without using a loop, whilst keeping the keys intact. Thanks again.
[eluser]Dam1an[/eluser]
Would this not cause a problem when both arrays have the same key (eg both have index 0)? Would you expect to overwrite it, increment the key of one to avoid crash etc?
[eluser]TheFuzzy0ne[/eluser]
OK, I think I've solved it. Code: print_r($arr1 + $arr2); I'd still be interested to know what PHP function the + construct calls, though.
[eluser]TheFuzzy0ne[/eluser]
[quote author="Dam1an" date="1243963231"]Would this not cause a problem when both arrays have the same key (eg both have index 0)? Would you expect to overwrite it, increment the key of one to avoid crash etc?[/quote] There wouldn't be a problem, as the keys are UIDs, but yes, if by some freak of nature the key existed, it should just be overwritten.
[eluser]Evil Wizard[/eluser]
[quote author="Dam1an" date="1243963231"]Would this not cause a problem when both arrays have the same key (eg both have index 0)? Would you expect to overwrite it, increment the key of one to avoid crash etc?[/quote] That could be avoided with Code: if(!count(array_diff_assoc($array1, $array2)) {
[eluser]xwero[/eluser]
The array_diff_key function could be used to merge arrays, it preserves the keys and if there is a non unique key found it will be removed.
[eluser]Dam1an[/eluser]
Looking on the php docs (here) that only seems to work one way :-S Code: <?php Code: array(2) { |
Welcome Guest, Not a member yet? Register Sign In |