array_merge() function merges arrays in php. It can combine multiple arrays into one array without changing the original array. It’s worth it, but today I encountered several small details when using array_merge to merge arrays. Let me give you an example below
1.array_merge() merge
$array = array('a'=>'bb'); $array2 = array('b'=>'cc'); $array3 = array_merge($array,$array2);
The output result is
Array ( [a] => bb [b] => cc )
There is no problem because the above are all arrays. If we set $array to not be an array, let’s see what happens.
$array = 1;//array('a'=>'bb'); $array2 = array('b'=>'cc'); $array3 = array_merge($array,$array2); print_r( $array3 );
After running The result
Warning: array_merge() [function.array-merge]: Argument #1 is not an array in E:test1.php on (www.jb51.net)line 4
tells us that we must have an array, so I have many ways to solve this,
1. Use is_array() to judge, but you will find that if you merge the arrays More often than not, each judgment is unreasonable. Later, I found that the data class can be converted
$array = 1;//array('a'=>'bb'); $array2 = array('b'=>'cc'); $array3 = array_merge((array)$array,(array)$array2); print_r( $array3 ); 输出结果不报错了 Array ( [0] => 1 [b] => cc )
. It automatically converted the number 1 into an array, so everyone must pay attention to these when using it. Oh the details.
Merge two arrays into one array:
<?php$a1=array("a"=>"red","b"=>"green");$a2=array("c"=>"blue","b"=>"yellow");print_r(array_merge($a1,$a2));?>
Definition and usage
array_merge() function is used to merge one or more arrays into one array.
Tip: You can input one or more arrays to the function.
Note: If two or more array elements have the same key name, the last element will overwrite the other elements.
Note: If you only input an array to the array_merge() function, and the keys are integers, the function will return a new array with integer keys whose keys start with 0 starts reindexing (see Example 1 below).
Tip: The difference between this function and the array_merge_recursive() function is that it handles the case where two or more array elements have the same key name. array_merge_recursive() will not perform key name overwriting, but will recursively form multiple values with the same key name into an array.
Syntax
array_merge(array1,array2,array3...)
array1 Required. Specifies an array.
array2 Optional. Specifies an array.
array3 Optional. Specifies an array.
Return the merged array.
Use only one parameter with an integer key name:
<?php$a=array(3=>"red",4=>"green");print_r(array_merge($a));?>
The above is the detailed content of php merge array function array_merge(). For more information, please follow other related articles on the PHP Chinese website!