How can PHP be used to create a stack data structure for storing values?
To create a stack data structure in PHP for storing values, we can utilize the built-in array functions to mimic the behavior of a stack. We can use array_push() to add elements to the top of the stack, array_pop() to remove elements from the top of the stack, and count() to get the number of elements in the stack.
class Stack {
private $stack;
public function __construct() {
$this->stack = [];
}
public function push($value) {
array_push($this->stack, $value);
}
public function pop() {
if (!$this->isEmpty()) {
return array_pop($this->stack);
}
}
public function isEmpty() {
return empty($this->stack);
}
public function size() {
return count($this->stack);
}
}
// Example usage
$stack = new Stack();
$stack->push(5);
$stack->push(10);
$stack->push(15);
echo $stack->pop(); // Output: 15
echo $stack->pop(); // Output: 10
echo $stack->size(); // Output: 1