How to Merge Two or More Arrays in to One Array in PHP?

PHP

Nicesnippets

04-06-2022


How to Merge Two or More Arrays in to One Array in PHP?

Hello Friends,

This tutorial will give you example of How to append one array to another in PHP?. if you want to see example of How does PHP Append Array Work? then you are a right place. you can understand a concept of how to merge array in php?. In this article, we will implement a How to Merge Two or More Arrays into One Array in PHP. follow bellow step for How to add elements to an empty array in PHP?.

This article will give you simple example of How to insert an item at the beginning of an array in PHP.

So, let's see bellow solution:

Example 1:


<?php

$subject = array("ENGLISH","MATH","SCIENCE","ECONOMICS");

$subject1 = array("HINDI","GUJRATI");

echo "This is a array one : ";

foreach ($subject as $value)

{

echo $value.",";

}

echo "<br><br>";

echo "This is a second array : ";

foreach ($subject1 as $value)

{

echo $value.",";

}

echo "<br><br>";

$subject2 = (array_merge($subject,$subject1));

echo "After the second array append is array one :";

foreach ($subject2 as $value)

{

echo $value.",";

}

?>

Output:

This is a array one : ENGLISH,MATH,SCIENCE,ECONOMICS

This is a second array : HINDI,GUJRATI

After the second array append is array one :ENGLISH,MATH,SCIENCE,ECONOMICS,HINDI,GUJRATI

Example 2:

<?php

$mobails = array("APPLE ","VIVO","OPPO","SAMSUMG");

$mobails1 = array("SONUY","MICROMAX");

echo "Original array one : ";

foreach ($mobails as $value)

{

echo $value.",";

}

echo "<br><br>";

echo "Original array second : ";

foreach ($mobails1 as $value1)

{

echo $value1.",";

}

echo "<br><br>";

array_push($mobails , ...$mobails1);

echo "After append second array in to array one :";

foreach ($mobails as $x)

{

echo "<b>".$x."</b>".",";

}

?>

Output:

Original array one : APPLE ,VIVO,OPPO,SAMSUMG

Original array second : SONUY,MICROMAX

After append second array in to array one :APPLE ,VIVO,OPPO,SAMSUMG,SONUY,MICROMAX

It will help you...