phparraysarray-merge

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

Solution

  • 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,
    )