PHP Array array_push() Function (With Examples)

In this tutorial, we will learn about the PHP array_push() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_push() Function

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

Syntax

The syntax of the array_push() function:

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

Parameters

The parameters of the array_push() function:

  • 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 mpageTU elements too.

Return Value

The return type of this method is int, it returns the new number of elements in the array.

Sample Input/Output

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 str_replace() Function Example 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

The output of the above example is:

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

PHP str_replace() Function Example 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

The output of the above example is:

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.

To understand the above examples, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.