Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

SplStack

Process values in last-in, first-out order. push and pop use the same end, so the newest value is removed first. top inspects that value without changing the count.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new SplStack()

Process values in last-in, first-out order. push and pop use the same end, so the newest value is removed first. top inspects that value without changing the count. Guard pop on an empty stack because it raises RuntimeException. The SplStack::isEmpty method returns true for an empty stack. After SplStack::push, use SplStack::top to inspect the most recent value without removal, while SplStack::pop returns and removes it.

$s=new SplStack(); $s->push("outer"); $s->push("inner");
echo json_encode([$s->top(),$s->count(),$s->pop(),$s->top(),$s->count()]);
echo PHP_EOL,json_encode([$s->isEmpty(),$s->pop(),$s->isEmpty()]);
["inner",2,"inner","outer",1]
[false,"outer",true]

Examples

<?php
$s=new SplStack(); $s->push("outer"); $s->push("inner");
echo json_encode([$s->top(),$s->count(),$s->pop(),$s->top(),$s->count()]);
echo PHP_EOL,json_encode([$s->isEmpty(),$s->pop(),$s->isEmpty()]);

Result

["inner",2,"inner","outer",1]
[false,"outer",true]

Sources