PHP standard library splstack stack

Time:2022-6-11

What are the characteristics of stack

The stack follows the last in first out principle (LIFO). This means that the stack has only one exit for pushing and popping elements. When we perform push or pop operations, we should pay attention to whether the stack is full or empty.

Stack method

  • push
  • pop
  • top
  • bottom
  • isEmpty
  • offsetSet
  • offsetGet
  • offsetExists
  • offsetUnset

code

<?php
header("Content-type:text/html; charset=utf-8");

$stack = new SplStack();

//LIFO
echo 'stack push',PHP_EOL;

//Stack
$stack->push('hello');
$stack->push('world');
$stack->push('web');
$stack[] = 'site';
$stack[] = 'devlop';


echo '***************',PHP_EOL;

//Set the value of the element (stack top) with index 0 to devlop, and traverse the stack
$stack->offsetSet(0, 'DEVLOP');
foreach($stack as $val) {
    echo $val,PHP_EOL;
}

echo '***************',PHP_EOL;
//View the number of stack elements
Echo 'there are', $stack->count(), 'elements', PHP_ EOL;
Echo 'in stack', count ($stack), 'elements', PHP_ EOL;

echo '***************',PHP_EOL;
//View stack top and bottom elements
Echo 'the top element of the stack is', $stack->top(), PHP_ EOL;
Echo 'the element at the bottom of the stack is', $stack->bottom(), PHP_ EOL;

echo '***************',PHP_EOL;
//Traversal stack
foreach($stack as $val) {
    echo $val,PHP_EOL;
}

echo '***************',PHP_EOL;
//Out of stack
while($stack->count() != 0) {
    Echo 'the top element of the stack is:', $stack->top(), PHP_ EOL;
    $stack->pop();
}

output

stack push
***************
DEVLOP
site
web
world
hello
***************
There are 5 elements in the stack
There are 5 elements in the stack
***************
Stack top element is devlop
The element at the bottom of the stack is hello
***************
DEVLOP
site
web
world
hello
***************
The stack top element is devlop
The stack top element is: Site
The top element of the stack is: Web
The top element of the stack is: World
The top element of the stack is: Hello

Reference source

Simple practice of splstack of PHP standard library SPL – Shaohua xiuxiao – blog Garden (cnblogs.com)

This work adoptsCC agreement, reprint must indicate the author and the link to this article