2 Ways Merge Two Array in PHP

Learn 2 ways to merge two arrays in PHP. This tutorial will show you how to merge arrays using the array_merge() function and + sign.

This article goes in detailed on how to merge two array in PHP. You will learn how to append two arrays in PHP. You will learn how to merge multiple array in PHP. You will do the following things for PHP merge two array example.

We will use array_merge() function and + sign to merge multiple array in PHP. I will give you simple two examples. 

So, let's see the simple code of how to merge array in PHP.

Example 1:

index.php

<?php
  
    $arrayOne = ["One", "Two", "Three"];
    $arrayTwo = ["Four", "Five"];
        
    $newArray = array_merge($arrayOne, $arrayTwo);
    
    var_dump($newArray);
  
?>

Output:

array(5) {

  [0]=> string(3) "One"

  [1]=> string(3) "Two"

  [2]=> string(5) "Three"

  [3]=> string(4) "Four"

  [4]=> string(4) "Five"

}

Example 2:

index.php

<?php
  
    $arrayOne = [1 => "One", 2 => "Two", 3 => "Three"];
    $arrayTwo = [4 => "Four", 5 => "Five"];
        
    $newArray = $arrayOne + $arrayTwo;
    
    var_dump($newArray);
  
?>

Output:

array(5) {

  [1]=> string(3) "One"

  [2]=> string(3) "Two"

  [3]=> string(5) "Three"

  [4]=> string(4) "Four"

  [5]=> string(4) "Five"

}

#php

2 Ways Merge Two Array in PHP
1.10 GEEK