← Back to all snippets
PHP

PHP Array Stack and Queue Operations

Master fundamental array modifications in PHP. This snippet shows how to add elements to the end (array_push) or beginning (array_unshift) and remove elements from the end (array_pop) or beginning (array_shift) of an array.

<?php
$items = ['apple', 'banana'];

// Add elements to the end (like a stack push)
array_push($items, 'cherry', 'date');
// $items is now ['apple', 'banana', 'cherry', 'date']

// Remove an element from the end (like a stack pop)
$lastItem = array_pop($items);
// $lastItem is 'date', $items is ['apple', 'banana', 'cherry']

// Add elements to the beginning (like a queue enqueue)
array_unshift($items, 'grape', 'fig');
// $items is now ['grape', 'fig', 'apple', 'banana', 'cherry']

// Remove an element from the beginning (like a queue dequeue)
$firstItem = array_shift($items);
// $firstItem is 'grape', $items is ['fig', 'apple', 'banana', 'cherry']
?>
How it works: This code illustrates how to manipulate arrays as if they were stacks or queues using built-in PHP functions. `array_push()` adds one or more elements to the end of an array, while `array_pop()` removes and returns the last element. Conversely, `array_unshift()` adds elements to the beginning, and `array_shift()` removes and returns the first element, effectively allowing queue-like behavior.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs