Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: merge two arrays while keeping keys instead of reindexing?

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 and the other has only integers).

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 and dynamic $staticIdentifications = array(  Users::userID => "USERID",  Users::username => "USERNAME" ); // get the dynamic vars, formatted: varID => varName $companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']); // merge the static and dynamic vars (*** BUT KEEP THE INT INDICES ***) $idVars = array_merge($staticIdentifications, $companyVarIdentifications); 
like image 909
Garrett Avatar asked Jul 20 '10 16:07

Garrett


People also ask

What is the best method to merge two PHP objects?

Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass. Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2.

How do you merge arrays?

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.


2 Answers

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, ) 
like image 89
SirDarius Avatar answered Sep 23 '22 02:09

SirDarius


Considering that you have

$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 values in the final output.

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

Array('1' => 'value1', '4' => 'value4', '6' => 'value3'); 
like image 45
CRK Avatar answered Sep 19 '22 02:09

CRK