Introduction

To join two or more arrays together to produce one big array, use array_merge() function.

This function takes one or more arrays as arguments, and returns the merged array.

The original array(s) are not affected.

Demo

<?php

$authors = array("A","B");
$moreAuthors = array("C","Milton");
print_r(array_merge($authors, $moreAuthors));
?>/*from w ww  . j  a  v  a 2 s.  c  om*/

Result

array_merge() joins the array elements of the arrays together to produce the final array.

array_merge() preserves the keys of associative arrays, so you can use it to add new key/value pairs to an associative array:

Demo

<?php

    $myBook = array("title"=> "Java",
                    "author"=> "John A",
                    "pubYear"=>  2018);

    $myBook = array_merge($myBook, array("numPages"=>  464));

    print_r ($myBook);/*ww  w  . j a va 2 s. c  om*/
?>

Result

If you add a key/value pair using a string key that already exists in the array, the original element gets overwritten.

This makes array_merge() handy for updating associative arrays:

Demo

<?php
    $myBook = array("title"=> "Java",
                    "author"=> "John A",
                    "pubYear"=>  2018);

$myBook = array_merge($myBook, array("title"=> "Javascript","pubYear"=>  2017));

print_r ($myBook);/*from   w ww .  j  a  v  a 2s.  co  m*/
?>

Result

An element with the same numeric key doesn't get overwritten; instead the new element is added to the end of the array and given a new index:

Demo

<?php
$authors = array("A","B","C","D");
$authors = array_merge($authors, array(0 => "Milton"));

print_r ($authors);//from   w ww  . j av a2 s  .  c  o m
?>

Result

You can use array_merge() to reindex a single numerically indexed array, simply by passing the array.

This is useful if you want to ensure that all the elements of an indexed array are consecutively indexed:

Demo

<?php

$authors = array(34 => "A", 12 => "B", 65 => "C", 47 =>  "D");

print_r(array_merge($authors));
?>/*from  w  w  w .j  a v  a 2  s  . c om*/

Result

Related Topic