PHP - Ds\Stack::peek() Function
The PHPDs\Stack::peek()function is used to retrieve the value that is present at the top of a current stack. As the stack follows the LIFO (Last In, First Out), the last element always be added on the top of a stack.
For example, if a stack contains three elements [10, 20, 30], the top element will be 30. If the current stack is empty ([]), this function will throw anUnderflowException.
Syntax
Following is the syntax of the PHP Ds\Stack::peek() function −
public Ds\Stack::peek(): mixed
Parameters
This function does not accept any parameter.
Return value
This function returns the value at the top of a stack.
Example 1
The following is the basic example of the PHP Ds\Stack::peek() function −
<?php $stack = new \Ds\Stack([10, 20, 30, 40]); echo "The stack elements are: \n"; print_r($stack); echo "The element present at top of the stack is: "; #using peek() function print_r($stack->peek()); ?>
Output
After executing the above program, the following output will be displayed −
The stack elements are:
Ds\Stack Object
(
[0] => 40
[1] => 30
[2] => 20
[3] => 10
)
The element present at top of the stack is: 40
Example 2
Following is another example of the PHP Ds\Stack::peek() function. This function is used to retrieve the element which is present at the top of this stack [("Tutorials", "Point", "India")] −
<?php
$stack = new \Ds\Stack();
$stack->push("Tutorials", "Point", "India");
echo "The stack elements are: \n";
print_r($stack);
echo "The element present at top of the stack is: ";
print_r($stack->peek());
?>
Output
After executing the above program, the following output will be displayed −
The stack elements are:
Ds\Stack Object
(
[0] => India
[1] => Point
[2] => Tutorials
)
The element present at top of the stack is: India
Example 3
If the current stack is empty ([]), the peek() function throws an "UnderflowException" −
<?php $stack = new \Ds\Stack([]); echo "The stack elements are: \n"; print_r($stack); echo "The element present at top of the stack is: "; print_r($stack->peek()); ?>
Output
The above program throws the following exception −
The stack elements are:
Ds\Stack Object
(
)
The element present at top of the stack is: PHP Fatal error:
Uncaught UnderflowException: Unexpected empty state in C:\Apache24\htdocs\index.php:6
Stack trace:
#0 C:\Apache24\htdocs\index.php(6): Ds\Stack->peek()
#1 {main}
thrown in C:\Apache24\htdocs\index.php on line 6