Two methods and differences of array merging in PHP

Source: Internet
Author: User

Two methods and differences of PHP array merging
If it is an associative array, the following:

Copy CodeThe code is as follows:
$a = Array (
' WHERE ' = ' uid=1 ',
' Order ' = ' uid ',
);
$b = Array (
' WHERE ' = ' uid=2 ',
' Order ' = ' uid desc ',
);



1. Array_merge, if two arrays have the same key, the latter one will overwrite the previous

Copy CodeThe code is as follows:
<?php
$c = Array_merge ($a, $b);
Var_export ($c);//The result is the same as the original $b
$d = Array_merge ($b, $a);
Var_export ($d);//The result is the same as the original $ A


2. The "+" operator, if the two array has the same key, the previous one will overwrite the following

Copy CodeThe code is as follows:
<?php
$c = $a + $b;
Var_export ($c);//The result is the same as the original $ A
$d = $b + $a;
Var_export ($d);//The result is the same as the original $b



If it is a numeric index array, as follows:

Copy CodeThe code is as follows:
$a = Array (
1 = ' 1111111 ',
2 = ' 222222222 '
);
$b = Array (
4 = ' 33333333333 ',
1 = ' 444444444 '
);


1. Array_merge. The effect resembles code foreach each array element and then presses each element into a new stack

Copy CodeThe code is as follows:
<?php
$c = Array_merge ($a, $b);
Var_export ($c);
$d = Array_merge ($b, $a);
Var_export ($d);


Output:
Array (
0 = ' 1111111 ',
1 = ' 222222222 ',
2 = ' 33333333333 ',
3 = ' 444444444 ',
)
Array (
0 = ' 33333333333 ',
1 = ' 444444444 ',
2 = ' 1111111 ',
3 = ' 222222222 ',
)
2. The "+" operator. The effect is similar to the code foreach each array element, then presses each element into a new stack, and if the same key already exists, does not process

Copy CodeThe code is as follows:
<?php
$c = $a + $b;
Var_export ($c);
$d = $b + $a;
Var_export ($d);


Output:
Array (
1 = ' 1111111 ',
2 = ' 222222222 ',
4 = ' 33333333333 ',
)
Array (
4 = ' 33333333333 ',
1 = ' 444444444 ',
2 = ' 222222222 ',
)

Two methods and differences of array merging in PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.