Maison  >  Article  >  développement back-end  >  PHP 数组相加和array_merge的区别

PHP 数组相加和array_merge的区别

WBOY
WBOYoriginal
2016-08-08 09:30:451171parcourir

PHP数组处理强大的功能导致了各种数据处理函数。

其中数组相加以及array_merge让笔者踩了个小坑。

一、请看demo1:

        public function action_test54(){
                $a = array(
                        '0'=>1567,
                        '1'=>1568,
                        '2'=>1569,
                        '3'=>1570,
                );
                $b = array(
                        '1'=>1571,
                        '2'=>1572,
                        '3'=>1573,
                        '4'=>1574
                );
                d($a + $b);
                dd(array_merge($a,$b));

        }

demo1输出:

<small>array</small>(5) (
    0 => <small>integer</small> 1567
    1 => <small>integer</small> 1568
    2 => <small>integer</small> 1569
    3 => <small>integer</small> 1570
    4 => <small>integer</small> 1574
)
<small>array</small>(8) (
    0 => <small>integer</small> 1567
    1 => <small>integer</small> 1568
    2 => <small>integer</small> 1569
    3 => <small>integer</small> 1570
    4 => <small>integer</small> 1571
    5 => <small>integer</small> 1572
    6 => <small>integer</small> 1573
    7 => <small>integer</small> 1574
)

结论:

$a + $b  增量覆盖

array_merge($a,$b) 合并

二、Demo2

        public function action_test54(){
                $a = array(
                        'a'=>1567,
                        'b'=>1568,
                        'c'=>1569,
                        'd'=>1570,
                );
                $b = array(
                        'b'=>1571,
                        'c'=>1572,
                        'd'=>1573,
                        'e'=>1574
                );
                d($a + $b);
                dd(array_merge($a,$b));

        }

Demo2输出:
<small>array</small>(5) (
    "a" => <small>integer</small> 1567
    "b" => <small>integer</small> 1568
    "c" => <small>integer</small> 1569
    "d" => <small>integer</small> 1570
    "e" => <small>integer</small> 1574
)
<small>array</small>(5) (
    "a" => <small>integer</small> 1567
    "b" => <small>integer</small> 1571
    "c" => <small>integer</small> 1572
    "d" => <small>integer</small> 1573
    "e" => <small>integer</small> 1574
)

结论:

$a + $b 增量覆盖

array_merger($a,$b) $b优先替换掉$a


以上就介绍了PHP 数组相加和array_merge的区别,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn