search
HomeBackend DevelopmentPHP TutorialSimilarities and Differences in Three PHP Methods of Merging Arrays_PHP Tutorial

1. "+" operator

Rule: When the key names of the two arrays are numeric key names or string key names, you can directly +, $c = $a + $b, append after $a ($b is a key that does not exist in $a name) key name and value.

Note:

  1. does not overwrite, just appends the non-existing key name and corresponding value.
  2. Key names are not re-indexed.
  3. Whether it is all numeric key names or mixed, only the key name and value are appended. If the key names are the same, no appending is performed, that is, the first appearing value is returned as the final result.
<?php
$fruit_1 = array( 'apple', 'banana' );
$fruit_2 = array( 'orange', 'lemon' );
$fruit = $fruit_1 + $fruit_2;
var_dump($fruit);
 
// output:
// array(2) { [0]=> string(5) "apple" [1]=> string(6) "banana" }
?>

Number key name:

<?php
$a = array( 66=>'a' );
$b = array( 60=>'u', 66=>'c' );
$c = $a + $b;
var_dump($c);
 
// output:
// array(2) { [66]=> string(1) "a" [60]=> string(1) "u" }
?>

Character key name:

<?php
$a = array( 1=>'a', 2=>'b', 'c'=>'c', 'd'=>'d' );
$b = array( 1=>'u', 3=>'v', 'c'=>'w', 'd'=>'x', 'y'=>'y', 60=>'z' );
$c = $a + $b;
var_dump($c);
 
// output:
// array(7) { [1]=> string(1) "a" [2]=> string(1) "b" ["c"]=> string(1) "c" ["d"]=> string(1) "d" [3]=> string(1) "v" ["y"]=> string(1) "y" [60]=> string(1) "z" }
?>

2. array array_merge ( array array1 [, array array2 [, array ...]] )

Rule: array_merge() merges the cells of one or more arrays, and the values ​​in one array are appended to the previous array. Returns the resulting array. If the input array has the same string key name, the value after the key name will overwrite the previous value. However, if the array contains numeric keys, the subsequent values ​​will not overwrite the original values, but will be appended to them. If only an array is given and the array is numerically indexed, the keys are re-indexed consecutively.

Note:

  1. Numeric index will not be overwritten. After the values ​​are merged, the key names will be re-indexed in a continuous manner
  2. String key name, the value after the key name will overwrite the previous value
<?php
$a = array( 'a' );
$b = array( 'u' );
$c = array_merge($a, $b);
var_dump($c);
 
// output:
// array(2) { [0]=> string(1) "a" [1]=> string(1) "u" }
?>

Number key name:

<?php
$a = array( 66=>'a' );
$b = array( 60=>'u', 66=>'c' );
$c = array_merge($a, $b);
var_dump($c);
 
// output:
// array(3) { [0]=> string(1) "a" [1]=> string(1) "u" [2]=> string(1) "c" }
?>

Character key name:

<?php
$a = array( 1=>'a', 2=>'b', 'c'=>'c', 'd'=>'d' );
$b = array( 1=>'u', 3=>'v', 'c'=>'w', 'd'=>'x', 'y'=>'y', 60=>'z' );
$c = array_merge($a, $b);
var_dump($c);
 
// output:
// array(8) { [0]=> string(1) "a" [1]=> string(1) "b" ["c"]=> string(1) "w" ["d"]=> string(1) "x" [2]=> string(1) "u" [3]=> string(1) "v" ["y"]=> string(1) "y" [4]=> string(1) "z" }
?>

3. array array_merge_recursive ( array array1 [, array ...] )

array_merge_recursive() Merges the cells of one or more arrays, with the values ​​in one array appended to the previous array. Returns the resulting array.

If the input arrays have the same string key name, the values ​​will be merged into an array, which will go on recursively, so if a value itself is an array, this function will put it according to the corresponding entry. It is merged into another array.

However, if the arrays have the same array key name, the latter value will not overwrite the original value, but will be appended to it.

Note: The rules are basically the same as array_merge, except that recursive append is used when processing the same character key name.

<?php
$a = array( 'a' );
$b = array( 'u' );
$c = array_merge_recursive($a, $b);
var_dump($c);
 
// output:
// array(2) { [0]=> string(1) "a" [1]=> string(1) "u" }
?>

Number key name:

<?php
$a = array( 66=>'a' );
$b = array( 60=>'u', 66=>'c' );
$c = array_merge_recursive($a, $b);
var_dump($c);
 
// output:
// array(3) { [0]=> string(1) "a" [1]=> string(1) "u" [2]=> string(1) "c" }
?>

Character key name:

<?php
$a = array( 1=>'a', 2=>'b', 'c'=>'c', 'd'=>'d' );
$b = array( 1=>'u', 3=>'v', 'c'=>'w', 'd'=>'x', 'y'=>'y', 60=>'z' );
$c = array_merge_recursive($a, $b);
var_dump($c);
 
// output:
// array(8) { [0]=> string(1) "a" [1]=> string(1) "b" ["c"]=> array(2) { [0]=> string(1) "c" [1]=> string(1) "w" } ["d"]=> array(2) { [0]=> string(1) "d" [1]=> string(1) "x" } [2]=> string(1) "u" [3]=> string(1) "v" ["y"]=> string(1) "y" [4]=> string(1) "z" }
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752522.htmlTechArticle1. "+" operator rule: When the key names of the two arrays are numeric key names or string keys The name can be directly +, $c = $a + $b, append (the key name of $b does not exist in $a) key name and value after $a. ...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor