← Back to Chapters

PHP array_pop() & array_push()

? PHP array_pop() & array_push()

? Quick Overview

PHP provides two useful array manipulation functions: array_pop() and array_push(). These functions allow you to remove or add elements from the end of an array, making them ideal for stack-like operations and dynamic data handling.

? Key Concepts

  • array_pop() removes the last element of an array
  • array_push() adds one or more elements to the end
  • Both functions modify the original array
  • Commonly used in loops, stacks, and dynamic lists

? Syntax & Theory

? View Code Example
// Removes and returns the last element of an array
array_pop($array);

// Adds one or more elements to the end of an array
array_push($array, $value1, $value2);

? Live Stack Simulator

Add items to the "stack" (push) or remove the top item (pop).

Array is empty
Current PHP Array: []

? Code Example: array_pop()

array_pop() removes the last element from an array and returns it.

? View Code Example
// Removing the last fruit from the array
$fruits = array("Apple", "Banana", "Cherry");
$removed = array_pop($fruits);

echo $removed;
print_r($fruits);

? Output Explanation

The value Cherry is removed and stored in $removed. The remaining array contains Apple and Banana.

? Code Example: array_push()

array_push() adds new elements to the end of an array.

? View Code Example
// Adding new fruits to the array
$fruits = array("Apple", "Banana");
array_push($fruits, "Cherry", "Date");

print_r($fruits);

? Output Explanation

The array now contains four elements: Apple, Banana, Cherry, and Date.

? Interactive Concept (Stack Behavior)

Think of array_push() as push and array_pop() as pop in a stack data structure.

? View Concept Code
// Simulating stack operations
$stack = array();

array_push($stack, "A");
array_push($stack, "B");
array_push($stack, "C");

array_pop($stack);
print_r($stack);

? Use Cases

  • Building stack and undo systems
  • Managing dynamic lists
  • Processing user input queues
  • Temporary storage during calculations

✅ Tips & Best Practices

  • Always check array size before using array_pop()
  • Use array_push() for adding multiple values efficiently
  • Prefer clear variable names when storing popped values

? Try It Yourself

  • Create an array of colors and remove the last color
  • Add multiple items to a shopping cart array
  • Simulate a stack using push and pop operations