Home » PHP

PHP array_push() function with example

PHP array_push() function: Here, we are going to learn about the array_push() function with example in PHP.
Submitted by IncludeHelp, on February 15, 2019

PHP array_push() function

array_push() function is used to insert/push one or more than one element to the array.

Syntax:

    array_push(array, elemement1, [element2],..);

Here,

  • array is the source array in which we have to push the elements.
  • element is the value to be added, we can add more than one elements too.

Examples:

    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" => "Amit", "age" => 21);
    
    array_push($arr, "Gwalior");
    array_push($arr, "Male", "RGTU University");
    
    print("array after inserting elements...\n");
    print_r($arr);
?>

Output

array after inserting elements...
Array             
(  
    [name] => Amit
    [age] => 21
    [0] => Gwalior
    [1] => Male
    [2] => RGTU University
) 

See the output – There are two keys name and age and we added three more elements "Gwalior", "Male" and "RGTU University", these three elements added with the keys 0, 1 and 2.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.