Skip to content
Related Articles

Related Articles

How to use array_pop() and array_push() methods in PHP ?

Improve Article
Save Article
  • Last Updated : 07 Oct, 2021
Improve Article
Save Article

The array_push() and array_pop() methods in PHP is used to perform insertions as well as deletions from the object. The article below illustrates the usage of these methods: 

Using array_push() Method: The array_push() method is used to push multiple elements in the array collection object. After each array_push() method, the size of the array object increases by the number of elements specified in the method call. 

array_push($array, $elements)

Parameters: 

  • $array – The array in which the elements are pushed.
  • $elements – The elements pushed in an array.

PHP




<?php
  
// Declaring an array
$arr = array();
  
// Adding the first element
array_push($arr, 1);
  
print("Array after first addition </br>");
print_r($arr);
print("</br>");
  
// Adding second element
array_push($arr, 2);
print("Array after second addition </br>");
print_r($arr);
  
?>


Output

Array after first addition </br>Array
(
    [0] => 1
)
</br>Array after second addition </br>Array
(
    [0] => 1
    [1] => 2
)

 

The array_push() method is used to push multiple elements in the array simultaneously. Elements are inserted in the order in which they are specified in the method call.  The following code snippet indicates the procedure: 

array_push($array, $ele1, $ele2, ...)

PHP




<?php
    
// Declaring an array
$arr = array();
  
// Adding the first element
array_push($arr, 1, 2, 3, 4, 5);
  
print_r("Array after multiple insertions </br>");
  
print_r($arr);
?>


Output

Array after multiple insertions </br>Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Using array_pop() Method: The array_pop() method is used to pop the elements from the array. The elements are removed from the end one by one each time when this method is called. 

array_pop($array)

Parameters: The function takes only one parameter $array, that is the input array, and pops out the last element from it, reducing the size by one.

PHP




<?php
    
// Declaring an array
$arr = array();
  
// Adding the first element
array_push($arr, 1, 2, 3, 4, 5);
  
print_r("Array after multiple insertions </br>");
print_r($arr);
array_pop($arr);
  
// Single array pop
print_r("Array after a single pop </br>");
print_r($arr);
  
?>


Output

Array after multiple insertions </br>Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array after a single pop </br>Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!