PHP append to array program

PHP append to array program – In programming we come to a situation where need to append array or some data to existing array. In PHP there are many built-in functions which can solve our purpose. We can merge an array to another array or can push a value to an array, depends upon the situation. So let us try with simple program.

Example:

Input :        arry1 = [9,5,8]
               arry2 = [20,25] 
               
               
Output :      arry1 = [9,5,8,20,25]               


Input :        arry1 = ["bptutorials.com"]
               arry2 = ["php", "mysql", "python"] 
               
               
Output :      arry1 = ["bptutorials.com","php","mysql","python"]  

Using array_merge() function :

This built-in function merge two arrays and returns a new array.

Syntax :

array_merge($array1, $array2);

Program source code :

<?php
/******************************************************************************

PHP append to array program

https://bptutorials.com

*******************************************************************************/

$arry1 = array(9,5,8);
$arry2 = array(20,25);
$merge_array = array_merge($arry1, $arry2);
print_r($merge_array);

Output :

Array
(
    [0] => 9
    [1] => 5
    [2] => 8
    [3] => 20
    [4] => 25
)

Using array_push() function :

This function push one or more elements at the end of first array.

$array1 = array('Mango', 'Apple', 'Grape','Water Melon');
$array2 = array('Kale','Cabbage','Ladies Finger');
array_push($array1, $array2);
print_r($array1);

Output :

Array
(
    [0] => Mango
    [1] => Apple
    [2] => Grape
    [3] => Water Melon
    [4] => Array
        (
            [0] => Kale
            [1] => Cabbage
            [2] => Ladies Finger
        )

)

Using Square Brackets :

Easy way to append to the array. But only one argument accept. No need to call any inbuild function.

$arr1= array(
    'HP',
    'Lenovo',
    'Dell'
);

// Add element to arr1 at end
$arr1[] = 'Asus';

//Output
print_r($arr1);


Output :

Array
(
    [0] => HP
    [1] => Lenovo
    [2] => Dell
    [3] => Asus
)
Share This!

Leave a Reply

Your email address will not be published.