Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 30 / 68

Stacks and Queues (Basic Data Structures)

In this lesson you will learn the difference between a stack and a queue, and how to build each one in PHP. This is for anyone searching for "PHP stack queue implementation".

A stack is "last in, first out" and a queue is "first in, first out". The difference between a pile of books and a queue of people is a helpful picture.

The sample code builds a stack by adding to the end with array_push() and taking from the end with array_pop(), and a queue by adding to the end with array_push() and taking from the front with array_shift().

A common stumbling block for beginners is the difference between array_pop() and array_shift(). Both remove one element, but pop takes it from the end and shift from the front. Miss that and the items come out in the wrong order.

Which structure you pick changes the order of processing and the efficiency of your algorithm considerably. The standard library also provides dedicated SplStack and SplQueue classes, which serious implementations sometimes prefer.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)