0
0
PHPprogramming~5 mins

Array push and pop in PHP

Choose your learning style9 modes available
Introduction

We use push and pop to add or remove items from the end of a list. This helps us manage collections of things easily.

When you want to add a new item to the end of a list, like adding a new song to a playlist.
When you want to remove the last item from a list, like taking the last book off a stack.
When you need to keep track of things in order, adding and removing from the end only.
When you want to use a list like a stack, where the last thing added is the first to be removed.
Syntax
PHP
<?php
// Define an array
$array = [];

// Add item to the end
array_push($array, $item);

// Remove item from the end
$popped_item = array_pop($array);
?>

array_push adds one or more items to the end of the array.

array_pop removes and returns the last item from the array.

Examples
This adds 'apple' to an empty array, so the array now has one item.
PHP
<?php
// Example: Push items to an empty array
$array = [];
array_push($array, 'apple');
print_r($array);
?>
This removes 'apple' from the array and prints it. The array becomes empty.
PHP
<?php
// Example: Pop item from an array with one element
$array = ['apple'];
$popped = array_pop($array);
echo $popped . "\n";
print_r($array);
?>
This adds 'banana' and 'cherry' to the end of the array.
PHP
<?php
// Example: Push multiple items
$array = ['apple'];
array_push($array, 'banana', 'cherry');
print_r($array);
?>
Trying to pop from an empty array returns NULL.
PHP
<?php
// Example: Pop item from an empty array
$array = [];
$popped = array_pop($array);
var_dump($popped);
?>
Sample Program

This program starts with an empty array, adds three fruits, removes the last one, and prints the array before and after.

PHP
<?php
// Create an empty array
$fruits = [];

// Show initial state
echo "Initial array:\n";
print_r($fruits);

// Push items
array_push($fruits, 'apple');
array_push($fruits, 'banana', 'cherry');

echo "\nAfter pushing items:\n";
print_r($fruits);

// Pop an item
$popped_fruit = array_pop($fruits);
echo "\nPopped item: $popped_fruit\n";

// Show final state
echo "\nFinal array:\n";
print_r($fruits);
?>
OutputSuccess
Important Notes

Time complexity: Both array_push and array_pop work in constant time O(1).

Space complexity: array_push may increase array size, array_pop reduces it.

Common mistake: Forgetting that array_pop returns the removed item, so you can save it if needed.

Use push/pop when you only add or remove from the end. For other positions, use different functions.

Summary

array_push adds items to the end of an array.

array_pop removes and returns the last item from an array.

These functions help manage lists like stacks easily.