Home >Backend Development >PHP Tutorial >How Can I Preserve Keys While Merging Arrays in PHP?
Your code aims to merge two arrays, one with string-keyed pairs and the other with integer-keyed pairs, while preserving the original keys. The issue arises because the default array_merge() function reindexes the resulting array, losing the desired key structure.
To overcome this challenge, you can leverage the array addition ( ) operator in PHP. This operator concatenates arrays while maintaining their original keys. By adding the two arrays, you effectively merge them while respecting the string and integer keys.
Your provided code can be modified as follows:
$staticIdentifications = array( Users::userID => "USERID", Users::username => "USERNAME" ); $companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']); $idVars = $staticIdentifications + $companyVarIdentifications;
Now, the $idVars array will contain the merged elements, with the string keys from $staticIdentifications and the integer keys from $companyVarIdentifications.
The above is the detailed content of How Can I Preserve Keys While Merging Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!