Home > Backend Development > PHP Tutorial > How to Merge PHP Arrays while Preserving Keys?

How to Merge PHP Arrays while Preserving Keys?

DDD
Release: 2024-11-15 09:18:02
Original
771 people have browsed it

How to Merge PHP Arrays while Preserving Keys?

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

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!

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