LIFO stands for Last In, First Out and is a principle of data structure management where the last element added is the first one to be removed. This method is commonly used in stack data structures.
Here's a simple example of how a stack with LIFO principle can be implemented in PHP:
class Stack {
private $stack;
private $size;
public function __construct() {
$this->stack = array();
$this->size = 0;
}
// Push operation
public function push($element) {
$this->stack[$this->size++] = $element;
}
// Pop operation
public function pop() {
if ($this->size > 0) {
return $this->stack[--$this->size];
} else {
return null; // Stack is empty
}
}
// Peek operation (optional): returns the top element without removing it
public function peek() {
if ($this->size > 0) {
return $this->stack[$this->size - 1];
} else {
return null; // Stack is empty
}
}
}
// Example usage
$stack = new Stack();
$stack->push("First");
$stack->push("Second");
$stack->push("Third");
echo $stack->pop(); // Output:
In this example, a stack is created in PHP in which elements are inserted using the push method and removed using the pop method. The output shows that the last element inserted is the first to be removed, demonstrating the LIFO principle.