How to Merge PHP Arrays with Key Preservation
In PHP, merging two arrays with string and integer keys using array_merge() can result in re-indexing. For scenarios where key preservation is essential, an alternative approach is available.
Solution: Using Array Addition
Instead of array_merge(), use the array addition operator ( ) to combine arrays. This operator appends the elements of the second array to the first array without modifying the keys.
Consider the following example:
// Static array with string keys $staticIdentifications = array( Users::userID => "USERID", Users::username => "USERNAME" ); // Dynamic array with integer keys $companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']); // Merge arrays while preserving keys $idVars = $staticIdentifications + $companyVarIdentifications;
In this case, $idVars will contain both the static and dynamic variables, preserving the original string and integer keys.
The above is the detailed content of How to Merge PHP Arrays while Preserving Keys?. For more information, please follow other related articles on the PHP Chinese website!