Notes for using the php array merge array_merge () function

Source: Internet
Author: User

1. array_merge () merge

Example

The code is as follows: Copy code

$ Array = array ('a' => 'BB ');
$ Array2 = array ('B' => 'CC ');
$ Array3 = array_merge ($ array, $ array2 );

The output result is

Array ([a] => bb [B] => cc)

The above is no problem because it is an array. Let's set $ array as an array to see what's going on.

The code is as follows: Copy code


$ Array = 1; // array ('a' => 'BB ');
$ Array2 = array ('B' => 'CC ');
$ Array3 = array_merge ($ array, $ array2 );
Print_r ($ array3 );

Running result

Warning: array_merge () [function. array-merge]: Argument #1 is not an array in E: test1.php on line 4

It tells us that an array is required, so there are many ways to solve this problem,

1. I used is_array () to determine the data type. However, I found that it is unreasonable to merge multiple arrays. Later I found that the data type can be converted.

The code is as follows: Copy code

$ Array = 1; // array ('a' => 'BB ');
$ Array2 = array ('B' => 'CC ');
$ Array3 = array_merge (array) $ array, (array) $ array2 );
Print_r ($ array3 );

No error is reported for the output.

Array ([0] => 1 [B] => cc)

He automatically converts number 1 to an array, so you must pay attention to these details when using it.

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.