PHP - Ds Stack::clear() Function



The PHP Ds\Stack::clear() function is used to remove all the values from the current stack. Once this function is called, the stack will be empty ([]), having no elements.

You can verify whether the stack is empty using the isEmpty() function. If the current stack is empty, this function returns true.

Syntax

Following is the syntax of the PHP Ds\Stack::clear() function −

public Ds\Stack::clear(): void

Parameters

This function does not accept any parameter.

Return value

This function does not return any value.

Example 1

The following program demonstrates the usage of the PHP Ds\Stack::clear() function −

<?php
   $stack = new \Ds\Stack([10, 20, 30]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The stack after calling the clear() function: \n";
   #using clear() function
   $stack->clear();
   print_r($stack);
?>

Output

After executing the above program, the following output will be displayed −

The stack elements are:
Ds\Stack Object
(
    [0] => 30
    [1] => 20
    [2] => 10
)
The stack after calling the clear() function:
Ds\Stack Object
(
)

Example 2

Following is another example of the PHP Ds\Stack::clear() function. We use this function to remove all the elements of this stack (["Tutorials", "Point", "India"]) −

<?php
   $stack = new \Ds\Stack(["Tutorials", "Point", "India"]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The stack after calling the clear() function: \n";
   #using clear() function
   $stack->clear();
   print_r($stack);
   echo "The number of elements present in stack is: ";
   print_r($stack->count());
?<

Output

The above program produces the following output −

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The stack after calling the clear() function:
Ds\Stack Object
(
)
The number of elements present in stack is: 0
php_function_reference.htm
Advertisements