How to use a stack in PHP

1 Answer

0 votes
// (LIFO: Last In, First Out)

$stack = new SplStack();

// Push elements onto the stack
$stack->push("A");
$stack->push("B");
$stack->push("C");
$stack->push("D");
$stack->push("E");

// Pop elements from the stack
echo $stack->pop() . "\n"; 
echo $stack->pop() . "\n"; 

echo "\n";

// Peek at the top element without removing it
echo $stack->top() . "\n";

echo "\n";

// Print all elements in the stack
foreach ($stack as $item) {
    echo $item . "\n";
}



/*
run:

E
D

C

C
B
A

*/

 



answered Aug 14, 2025 by avibootz

Related questions

1 answer 93 views
1 answer 90 views
90 views asked Aug 15, 2025 by avibootz
1 answer 93 views
1 answer 93 views
93 views asked Aug 15, 2025 by avibootz
4 answers 272 views
272 views asked Apr 1, 2021 by avibootz
2 answers 199 views
...