"USERID", Users::username => "USERNAME" ); // get the d" /> "USERID", Users::username => "USERNAME" ); // get the d" />

Merge array keys php

How can I merge two arrays (one with string => value pairs and another with int => value pairs) while keeping the string/int keys? None of them will ever overlap (because one has only strings và the other has only integers).

Bạn đang xem: Merge array keys php

Here is my current code (which doesn"t work, because array_merge is re-indexing the array with integer keys):

// get all id vars by combining the static & dynamic $staticIdentifications = array( Users::userID => "USERID", Users::username => "USERNAME" ); // get the dynamic vars, formatted: varID => varName $companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION<"companyID">); // merge the static & dynamic vars (*** BUT KEEP THE INT INDICES ***) $idVars = array_merge($staticIdentifications, $companyVarIdentifications);
That's odd: according to lớn the PHPhường. doc page, array_merge shouldn't vị that. Are the string keys actually string representations of integers? – owenmarshall Jul 20 "10 at 16:16
array_merge is reindexing my second array. ie. it is changing the array from array( 123 => "VALUE123" ) lớn array( 0 => "VALUE123" ) – Garrett Jul đôi mươi "10 at 16:16
hmm, that is interesting. I suppose that the PHPhường documentation could be a little unclear on that point. It says what will happen if all of the arrays have numeric keys, but it doesn't specifically say what will happen if they don't. – Steven Oxley Jul trăng tròn "10 at 16:25
maybe not 2 years ago. But in 2012, the documentation is Crystal clear on this point. – cartbeforehorse May 15 "12 at 8:32
Actually, the documentation is still not crystal clear. "Numeric" actually includes a string with all digits (PHPhường. 5.3.3). assert(array(0=>0,1=>1) === array_merge(array('9'=>0), array('9'=>1))) – Bob Stein Feb 11 "13 at 3:27

You can simply "add" the arrays:

>> $a = array(1, 2, 3); array ( 0 => 1, 1 => 2, 2 => 3, ) >> $b = array("a" => 1, "b" => 2, "c" => 3) array ( "a" => 1, "b" => 2, "c" => 3, ) >> $a + $b array ( 0 => 1, 1 => 2, 2 => 3, "a" => 1, "b" => 2, "c" => 3, )
Be VERY careful with this! The + operator is not an addition, it's a union. If the keys don't overlap then all is good, but if they vị... – GordonM May 3 "12 at 15:46

Just wow - you saved me buckets of lines of code, nearly three years on. – Stephen O'Flynn Feb 8 "13 at 18:13

In case anyone wonders 'what if they DO overlap?' : php.net: "The + operator returns the right-h& array appended lớn the left-h& array; for keys that exist in both arrays, the elements from the left-hvà array will be used, & the matching elements from the right-h& array will be ignored." – Flion Sep 18 "13 at 16:24

Flion it's more complicated than that. Using '+', I have just added two sub-arrays with an element with a comtháng key & subkey: the values got added! 100000 => array (size=3) 1 => int 128 2 => int 56 3 => int 7 + 100000 => array (size=1) 2 => int 30 Result: 100000 => array (size=3) 1 => int 128 2 => int 86 3 => int 7 Basically adding <2 => 56> + <2 => 30> did not replace the value but added it and became <2 => 86> – Dario Fumagalli Nov 30 "16 at 1:20

DarioFumagalli I don't know if I'm misunderstanding or if it's just changed since năm nhâm thìn, but at this point in time, the operation print_r(<2 => 56> + <2 => 30>); yields Array ( <2> => 56 ). So, it's keeping the left hvà side as specified. This is as of PHP.. 7.1.19, running on repl.it. – Charles Wood Jun 27 "19 at 20:34


Considering that you have sầu

$replaced = array("1" => "value1", "4" => "value4"); $replacement = array("4" => "value2", "6" => "value3");

Doing $merge = $replacement + $replaced; will output:

Array("4" => "value2", "6" => "value3", "1" => "value1");

The first array from sum will have sầu values in the final output.

Doing $merge = $replaced + $replacement; will output:

Array("1" => "value1", "4" => "value4", "6" => "value3");
<> on this one – Jhourlad Estrella Jul 19 "13 at 8:38

To sum up, when adding 2 arrays, values from the first override values from the second. – Dziamid Oct 31 "13 at 14:10

I thought the second will override the first. :) – Asyên K T Oct 9 "17 at 6:24

Exactly. That's why I couldn't use $allValues += $newValues;. – MarthyM Oct 10 "17 at 13:01
Doing $merge = $replacement + $replaced; will output: Array ( <4> => value2 <6> => value3 <1> => value1 ) – Chandan Sharma Oct 19 "19 at 5:39


While this question is quite old I just want to add another possibility of doing a merge while keeping keys.

Besides adding key/values to existing arrays using the + sign you could bởi vì an array_replace.

$a = array("foo" => "bar", "some" => "string"); $b = array(42 => "answer to lớn the life and everything", 1337 => "leet"); $merged = array_replace($a, $b);

The result will be:

Array ( => bar => string <42> => answer lớn the life and everything <1337> => leet )

Same keys will be overwritten by the latter array. There is also an array_replace_recursive sầu, which vị this for subarrays, too.

Live sầu example on 3v4l.org


Two arrays can be easily added or union without chaning their original indexing by + operator. This will be very help full in laravel and codeigniter select dropdown.

$empty_option = array( ""=>"Select Option" ); $option_list = array( 1=>"Red", 2=>"White", 3=>"Green", ); $arr_option = $empty_option + $option_list;

đầu ra will be :

$arr_option = array( ""=>"Select Option" 1=>"Red", 2=>"White", 3=>"Green", );

Try array_replace_recursive or array_replace functions

$a = array("userID" => 1, "username"=> 2); array ( userID => 1, username => 2 ) $b = array("userID" => 1, "companyID" => 3); array ( "userID" => 1, "companyID" => 3 ) $c = array_replace_recursive($a,$b); array ( userID => 1, username => 2, companyID => 3 )

http://php.net/manual/en/function.array-replace-recursive sầu.php


Hello year 2010 question.

Xem thêm: lỗi không include được file php

The OPhường."s requirement is preserve sầu keys (keep keys) & not overlap (I think overwrite). In some case such as numeric keys it is possible but if string keys it seems to lớn be not possible.

If you use array_merge() the numeric keys will always re-index or renumbered. If you use array_replace(), array_replace_recursive() it will be overlap or overwrite from the right to lớn the left. The value with the same key on first array will be replaced with second array. If you use $array1 + $array2 as the phản hồi was mentioned, if the keys are same then it will keep the value from first array but drop the second array.

Custom function.

Here is my function that I just wrote to work on the same requirements. You are không lấy phí to lớn use for any purpose.

Xem thêm: Danball Senki Boost Rom - Danball Senki W Japan Iso Rom Download For Psp

/** * Array custom merge. Preserve sầu indexed array key (numbers) but overwrite string key (same as PHP"s `array_merge()` function). * * If the another array key is string, it will be overwrite the first array.
* If the another array key is integer, it will be add to lớn first array depend on duplicated key or not. * If it is not duplicate key with the first, the key will be preserve và add to the first array. * If it is duplicated then it will be re-index the number append to the first array. * *
param array $array1 The first array is main array. *
param array ...$arrays The another arrays to merge with the first. *
return array Return merged array. */ function arrayCustomMerge(array $array1, array ...$arrays): array elseif (is_int($key) && !array_key_exists($key, $array1)) else }// endforeach; $additionalArray unset($thành tựu, $key); }// endforeach; unset($additionalArray); return $array1; }// arrayCustomMerge

Testing.

"apple", 3.1 => "dog", null => "null", >; $array2 = < 1 => "polar bear", đôi mươi => "monkey", "fruitred" => "strawberry", "fruityellow" => "banana", null => "another null", >; // require `arrayCustomMerge()` function here. function printDebug($message) eđến "array1:
"; printDebug($array1); emang đến "array2:
"; printDebug($array2); eđến PHP_EOL . "
" . PHP_EOL . PHP_EOL; eđến "arrayCustomMerge:
"; $merged = arrayCustomMerge($array1, $array2); printDebug($merged); assert($merged<0> == "cat", "array key 0 should be "cat""); assert($merged<1> == "bear", "array key 1 should be "bear""); assert($merged<"fruitred"> == "strawberry", "array key "fruitred" should be "strawberry""); assert($merged<3> == "dog", "array key 3 should be "dog""); assert(array_search("another null", $merged) !== false, ""another null" should be merged."); assert(array_search("polar bear", $merged) !== false, ""polar bear" should be merged."); assert($merged<20> == "monkey", "array key 20 should be "monkey""); assert($merged<"fruityellow"> == "banana", "array key "fruityellow" should be "banana""); The results. array1: Array ( <0> => cat <1> => bear => hãng apple <3> => dog <> => null ) array2: Array ( <1> => polar bear <20> => monkey => strawberry => banana <> => another null ) --- arrayCustomMerge: Array ( <0> => mèo <1> => bear => strawberry <3> => dog <> => another null <4> => polar bear <20> => monkey => banamãng cầu )

Chuyên mục: