Home >Backend Development >PHP Tutorial >How to Merge Arrays with String and Integer Keys in PHP?

How to Merge Arrays with String and Integer Keys in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 09:21:02892browse

How to Merge Arrays with String and Integer Keys in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn