Dear Mates, Please click the ads to support us.

How to Append One Array to Another in PHP?

Kailash Singh

How to Append One Array to Another in PHP?

Published Aug 31,2022 by Kailash Singh

0 Comment     1135 Views    


In this tutorial, we are going to teach you how to append one array to another in PHP?.

 

Example 1:

In this example, we are using array_merge function. The array_merge() function merges one or more arrays into one array.

<?php   
    
    $fruits = array("Apple","Orange","Banana","Peaches");
    $fruits1 = array("Mangoes","Apricots");

    echo "This is a array one : ";

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

    
    echo "<br><br>";

    echo "This is a second array : ";

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

    echo "<br><br>";        

    $fruits2 = (array_merge($fruits,$fruits1));
    echo "After the second array append is array one :";
    
    foreach ($fruits2 as $value) 
    {
        echo $value.",";            
    } 

?>

 

Output:

This is a array one : Apple,Orange,Banana,Peaches,

This is a second array : Mangoes,Apricots,

After the second array append is array one :Apple,Orange,Banana,Peaches,Mangoes,Apricots,

 

Example 2:

In this example, we are using array_push function. The array_push() function inserts one or more elements to the end of an array.

<?php   
    
    $fruits = array("Apple","Orange","Banana","Peaches");
    $fruits1 = array("Mangoes","Apricots");

    echo "This is a array one : ";

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

    
    echo "<br><br>";

    echo "This is a second array : ";

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

    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:

This is a array one : Apple,Orange,Banana,Peaches,

This is a second array : Mangoes,Apricots,

After append second array in to array one :Apple,Orange,Banana,Peaches,Mangoes,Apricots,

 


Comments ( 0 )