-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.php
More file actions
49 lines (41 loc) · 1010 Bytes
/
stack.php
File metadata and controls
49 lines (41 loc) · 1010 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
class Stack {
private $stack;
public function __construct() {
$this->stack = [];
}
public function push($item) {
array_push($this->stack, $item);
}
public function pop() {
if ($this->isEmpty()) {
return "empty stack";
}
return array_pop($this->stack);
}
public function peek() {
if ($this->isEmpty()) {
return "empty stack";
}
return end($this->stack);
}
public function isEmpty() {
return empty($this->stack);
}
public function size() {
return count($this->stack);
}
}
// Example
$stack = new Stack();
$stack->push(1);
$stack->push(2);
$stack->push(3);
echo "Stack after pushing: ";
print_r($stack);
echo "Let's take a peek on the top: " . $stack->peek() . PHP_EOL;
echo "Popped item: " . $stack->pop() . PHP_EOL;
echo "Stack after popping: ";
print_r($stack);
echo "Is stack empty? " . ($stack->isEmpty() ? 'true' : 'false') . PHP_EOL;
?>