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

Barbara Streisand
Release: 2024-11-14 09:21:02
Original
767 people have browsed it

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;
Copy after login

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,
]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template