Merging Arrays with String and Integer Keys in PHP
To merge two arrays in PHP while preserving their string and integer keys, you can use the array addition operator ( ). Unlike array_merge, which re-indexes arrays with integer keys, adding arrays appends the second array to the first, retaining the existing keys.
For example:
$staticIdentifications = [ Users::userID => "USERID", Users::username => "USERNAME" ]; $companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']); $idVars = $staticIdentifications + $companyVarIdentifications;
In this scenario, $idVars will be an array with both string and integer keys, similar to:
[ 0 => 1, 1 => 2, 2 => 3, 'a' => 1, 'b' => 2, 'c' => 3, ]
Note that the string keys are preserved, and the integer keys are appended after the existing keys. This approach allows you to merge arrays with different types of keys while maintaining the original structure and associations.
The above is the detailed content of How to Merge Arrays with String and Integer Keys in PHP?. For more information, please follow other related articles on the PHP Chinese website!