Home > Backend Development > PHP Tutorial > How Can I Preserve Keys While Merging Arrays in PHP?

How Can I Preserve Keys While Merging Arrays in PHP?

DDD
Release: 2024-11-14 21:43:02
Original
714 people have browsed it

How Can I Preserve Keys While Merging Arrays in PHP?

Preserving Keys During Array Merging 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.

Solution: Array Addition

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.

Example Usage

Your provided code can be modified as follows:

$staticIdentifications = array(
    Users::userID => "USERID",
    Users::username => "USERNAME"
);
$companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']);
$idVars = $staticIdentifications + $companyVarIdentifications;
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template