How to Append One Array to Another in PHP?

Jun 04, 2022 . Admin



Hello Friends,

This tutorial will provide example of How to append one array to another in PHP?. This article goes in detailed on How does PHP Append Array Work?. This article goes in detailed on how to merge array in php?. We will look at example of How to Merge Two or More Arrays into One Array in PHP?.

This article will give you simple example of How to append one array to another in PHP.

So, let's see bellow solution:

Example 1:
<?php   
    
    $laptops = array("LENOVO","HP","DELL","ASUS");
    $laptops1 = array("APPLE","TOSHIBA");

    echo "This is a array one : ";

    foreach ($laptops as $value) 
    {
        echo $value.",";    
    }

    
    echo "<br><br>";

    echo "This is a second array : ";

    foreach ($laptops1 as  $value) 
    {
        echo $value.",";    
    }

    echo "<br><br>";        

    $laptops2 = (array_merge($laptops,$laptops1));
    echo "After the second array append is array one :";
    
    foreach ($laptops2 as $value) 
    {
        echo $value.",";            
    } 

?>
    
Output:

This is a array one : LENOVO,HP,DELL,ASUS

This is a second array : APPLE,TOSHIBA

After the second array append is array one :LENOVO,HP,DELL,ASUS,APPLE,TOSHIBA

Example 2:
<?php 
    
    $fruits = array( "MANGO" , "BANANA" , "ORENG" , "APPLE");
    $fruits1 = array("CHERRY","GRAPE");

    echo "Original array one : ";

    foreach ($fruits as $value) 
    {
        echo $value.",";
    }        

    echo "<br><br>";

    echo "Original array second : ";

    foreach ($fruits1 as $value1) 
    {
        echo $value1.",";
    }        

    echo "<br><br>";

    array_push($fruits , ...$fruits1); 

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

    foreach ($fruits as $x)
    {
        echo "<b>".$x."</b>".",";
    }

?>
Output:
Original array one : MANGO,BANANA,ORENG,APPLE

Original array second : CHERRY,GRAPE

After append second array in to array one :MANGO,BANANA,ORENG,APPLE,CHERRY,GRAPE

It will help you...

#PHP