PHP
Manipulate Array Ends Like a Stack/Queue
Learn to add or remove elements from the beginning or end of a PHP array using array_unshift, array_shift, array_push, and array_pop, mimicking stack/queue behavior.
<?php
$queue = ['task1', 'task2', 'task3'];
echo "Original Queue: ";
print_r($queue);
// Add to the end (Queue: Enqueue)
array_push($queue, 'task4');
echo "After array_push (task4): ";
print_r($queue);
// Remove from the beginning (Queue: Dequeue)
$nextTask = array_shift($queue);
echo "Removed task: {$nextTask}";
echo "
After array_shift: ";
print_r($queue);
$stack = ['itemA', 'itemB'];
echo "
Original Stack: ";
print_r($stack);
// Add to the end (Stack: Push)
array_push($stack, 'itemC');
echo "After array_push (itemC): ";
print_r($stack);
// Remove from the end (Stack: Pop)
$lastItem = array_pop($stack);
echo "Popped item: {$lastItem}";
echo "
After array_pop: ";
print_r($stack);
// Add to the beginning (less common for stack/queue, but possible)
array_unshift($stack, 'itemX', 'itemY');
echo "
After array_unshift (itemX, itemY): ";
print_r($stack);
// Expected Output (variable based on execution):
// Original Queue: Array ( [0] => task1 [1] => task2 [2] => task3 )
// After array_push (task4): Array ( [0] => task1 [1] => task2 [2] => task3 [3] => task4 )
// Removed task: task1
// After array_shift: Array ( [0] => task2 [1] => task3 [2] => task4 )
//
// Original Stack: Array ( [0] => itemA [1] => itemB )
// After array_push (itemC): Array ( [0] => itemA [1] => itemB [2] => itemC )
// Popped item: itemC
// After array_pop: Array ( [0] => itemA [1] => itemB )
//
// After array_unshift (itemX, itemY): Array ( [0] => itemX [1] => itemY [2] => itemA [3] => itemB )
?>
How it works: PHP provides several functions to treat arrays as dynamic data structures like stacks (LIFO - Last In, First Out) and queues (FIFO - First In, First Out). `array_push()` adds elements to the end and `array_pop()` removes from the end. `array_unshift()` adds elements to the beginning, and `array_shift()` removes from the beginning. These functions are essential for managing lists where order of addition/removal matters, such as processing jobs or maintaining history.