CKTIS / PHP
SplStack::push — Add a value to the top of a stack
Use push() to add one value to an existing SplStack. The next pop() removes and returns that value if the top of the stack has not changed in the meantime.
Version: PHP 8.3
Syntax
public function SplDoublyLinkedList::push(mixed $value): void
$stack = new \SplStack();
$stack->push($value);SplStack::push is a public instance method inherited from SplDoublyLinkedList. The call $stack->push($value) appends an element to the tail of the doubly linked list, which is the top of the stack. The :: notation identifies the method; it does not make it a static call. The class is part of SPL, which is always enabled in standard PHP 8.3 and cannot be disabled through PHP configuration. new \SplStack() selects the class in the global namespace.
Each call takes exactly one mixed value, including null. An array passed as $value becomes one element, not a batch of separate elements. The method changes the existing object and returns void: it gives you neither an element count nor a stack for chaining calls.
pop() removes and returns a value from the same end, so pairing push() with pop() gives last-in, first-out (LIFO) behavior. top() returns the top value without removing it. Both methods throw \RuntimeException on an empty stack; use isEmpty() first if the stack might be empty. The iterator mode does not determine which end push() and pop() use.
Examples
<?php
$stack = new \SplStack();
$stack->push('first');
$stack->push('second');
echo 'top: ', $stack->top(), "\n";
while (!$stack->isEmpty()) {
echo 'pop: ', $stack->pop(), "\n";
}
Result
top: second pop: second pop: first
`second` appears twice: `top()` reads it, and the first `pop()` removes it. The next `pop()` removes `first`. The loop stops before it can call `pop()` on an empty stack.
Related lessons
- PHP · Lesson 64 · Advanced · Version: 2