views:

87

answers:

2

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 reindexing 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);

thanks!

+3  A: 

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,
)
SirDarius
WOW no way! operator overloading in php ftw! thanks =)
Garrett
A: 

The array union operator may do what you want (+). You could try $idVars = $staticIdentifications + $companyVarIdentifications. However, I suspect that you might be mistaken about your keys because array_merge should preserve keys unless all of the array keys are only numeric (PHP documentation).

Steven Oxley