Home > Backend Development > PHP Tutorial > php数组合并array_merge()函数使用注意事项_PHP

php数组合并array_merge()函数使用注意事项_PHP

WBOY
Release: 2016-06-01 11:50:45
Original
887 people have browsed it

1.array_merge()合并

例子

$array = array('a'=>'bb');
$array2 = array('b'=>'cc');
$array3 = array_merge($array,$array2);
输出结果为
Array ( [a] => bb [b] => cc )
Copy after login

上面因为都是数组就没有问题了,假如我们把$array 设置不是数组看看什么情况

$array = 1;//array('a'=>'bb');
$array2 = array('b'=>'cc');
$array3 = array_merge($array,$array2);
print_r( $array3 );
Copy after login


运行后结果

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

告诉我们必须是要一个数组了,那么这个我就有多种方法来解决,

1.使用is_array() 进行判断了,但是会发现如果合并数组比较多一个个判断不合理,后来发现可以转换数据类型

$array = 1;//array('a'=>'bb');
$array2 = array('b'=>'cc');
$array3 = array_merge((array)$array,(array)$array2);
print_r( $array3 );
输出结果不报错了
Array ( [0] => 1 [b] => cc )

Copy after login

他自动把数字1转换成了数组了,所以大家在使用时一定要注意这些细节哦。

Related labels:
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