In PHP there are two ways to use an array as a stack (LIFO)
and two ways to use them as a queue (FIFO).
One could implement a stack with push
& pop
,
but the same can be done with unshift
& shift
.
Similarly one could implement a queue with push
& shift
,
but the same can be done with unshift
& pop
.
To demonstrate:
echo "stack push & pop approach:\n";
$s = []; array_push($s, 'first'); array_push($s, 'second'); array_push($s, 'third');
echo array_pop($s) . '-' . array_pop($s) . '-' . array_pop($s) . "\n";
echo "stack unshift & shift approach:\n";
$s = []; array_unshift($s, 'first'); array_unshift($s, 'second'); array_unshift($s, 'third');
echo array_shift($s) . '-' . array_shift($s) . '-' . array_shift($s) . "\n";
echo "queue push & shift approach:\n";
$q = []; array_push($q, 'first'); array_push($q, 'second'); array_push($q, 'third');
echo array_shift($q) . '-' . array_shift($q) . '-' . array_shift($q) . "\n";
echo "queue unshift & pop approach:\n";
$q = []; array_unshift($q, 'first'); array_unshift($q, 'second'); array_unshift($q, 'third');
echo array_pop($q) . '-' . array_pop($q) . '-' . array_pop($q) . "\n";
Which outputs:
stack push & pop approach:
third-second-first
stack unshift & shift approach:
third-second-first
queue push & shift approach:
first-second-third
queue unshift & pop approach:
first-second-third
So which sets of functions to use?!