PHP array_push() function with example

PHP array_push() work: Here, we will find out about the array_push() work with the example in PHP.

array_push() work is utilized to embed/push at least one than one component to the cluster.

Syntax:

    array_push(array, elemement1, [element2],..);
  • cluster is the source exhibit in which we need to push the components.
  • the component is the value to be included, we can include more than one components as well.

Example:

    Input:
    //initial array is
    $arr = array(100, 200, 300);

    //pushing elements
    array_push($arr, 10);
    array_push($arr, 400, 500);
   
    Output:
    Array
    (    
        [0] => 100
        [1] => 200
        [2] => 300
        [3] => 10 
        [4] => 400
        [5] => 500
    )

PHP Code: 1 Inserting elements in an indexed array

<?php
    $arr = array(100, 200, 300);
    
    array_push($arr, 10);
    array_push($arr, 400, 500);
    
    print("array after inserting elements...\n");
    print_r($arr);
?>

Output

random key: age
array of random keys...
Array          
(              
    [0] => age 
    [1] => city
)

PHP code 2: Inserting elements in an associative array

<?php
    $arr = array("name" => "Kishan", "age" => 21);
    
    array_push($arr, "Bilaspur");
    array_push($arr, "Male", "GGU University");
    
    print("array after inserting elements...\n");
    print_r($arr);
?>

Output

array after inserting elements...
Array             
(  
    [name] => Kishan
    [age] => 21
    [0] => Bilaspur
    [1] => Male
    [2] => GGU University
)

See the output – There are two keys name and age and we included three additional components “Bilaspur”, “Male” and “GGU University”, these three components included with the keys 0, 1 and 2.

Leave a Comment

error: Alert: Content is protected!!