How To Use Array Merge Function With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

To merge two different array in php we need to use array_merge() is a builtin function.array_merge function used to merge two or more arrays into a single array.This function is used to merge the array elements or values of different arrays together into a single array.

merge two different array in php

Syntax PHP array_merge() Function

array_merge(array1, array2, array3, ...)
 

Parameter   Description
 

array1      Required. Specifies an input array
array2      Optional. Specifies an input array
array3,...  Optional. Specifies an input array


Exampe(1)

$array_1=array("a"=>"PHP","b"=>"Python","c"=>"embedded C");
$array_2=array("d"=>"HTML","e"=>"CSS","f"=>"JAVASCRIPT");
print_r(array_merge($array_1,$array_2));

In above example we have two different array as $array_1 and $array_2 with elements .By using array_merge() function we merged array elements after merging array element display array elements using print_r() function.


Complete code of array_merge() function.
 

<!DOCTYPE html>
<html>
<head>
    <title>How to merge two different array in php</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Merge Two Different Array in PHP</h1>
    </div>
    <br>
    <h2></h2>
    <div class="well">
        <?php
        $array_1=array("a"=>"PHP","b"=>"Python","c"=>"embedded C");
        $array_2=array("d"=>"HTML","e"=>"CSS","f"=>"JAVASCRIPT");
        print_r(array_merge($array_1,$array_2));
        foreach (array_merge($array_1,$array_2) as $ar){
            echo "<h1>".$ar."</h1>";
        }
        ?>
    </div>
</div>
</body>
</html>

Related Post