PHP - Ds Deque::shift() Function
The PHPDs\Deque::shift()function is used to remove the first element from the current deque and returns the first value that was removed.
The Ds\Deque class provides another function calledremove(), which is used to remove the element at the specified index if the index is 0, it removes the first element in deque.
Syntax
Following is the syntax of the PHP Ds\Deque::shift() function −
public mixed Ds\Deque::shift( void )
Parameters
This function does not accept any parameter.
Return value
This function returns the first value that is removed.
Example 1
The following is the basic example of the PHP Ds\Deque::shift() function −
<?php $deque = new \Ds\Deque([10, 20, 30, 40, 50]); echo "The deque elements are: \n"; print_r($deque); #using shift() function echo "The removed element is: "; print_r($deque->shift()); ?>
Output
The above program produces the following output −
The deque elements are:
Ds\Deque Object
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
[4] => 50
)
The removed element is: 10
Example 2
Following is another example of the PHP Ds\Deque::shift() function. We use this function to remove the first element in this deque (['a', 'e', 'i', 'o', 'u']) −
<?php $deque = new \Ds\Deque(['a', 'e', 'i', 'o', 'u']); echo "The deque elements are: \n"; print_r($deque); #using shift() function echo "The removed element is: "; print_r($deque->shift()); echo "\nThe deque after first element removed: \n"; print_r($deque); ?>
Output
After executing the above program, it will display the following output −
The deque elements are:
Ds\Deque Object
(
[0] => a
[1] => e
[2] => i
[3] => o
[4] => u
)
The removed element is: a
The deque after first element removed:
Ds\Deque Object
(
[0] => e
[1] => i
[2] => o
[3] => u
)
Example 3
In the example below, we use the shift() function to remove the first four elements one by one from the deque (["Tutorials", "Point", "Hyderabad", "India"]) −
<?php $deque = new \Ds\Deque (["Tutorials", "Point", "Hyderabad", "India"]); echo "After first shift operation: "; print_r($deque -> shift()); echo "\nAfter second shift operation: "; print_r($deque -> shift()); echo "\nAfter third shift operation: "; print_r($deque -> shift()); echo "\nAfter fourth shift operation: "; print_r($deque -> shift()); echo "\nThe deque after removing all elements one by one: \n"; print_r($deque); ?>
Output
On executing the above program, it will produce the following output −
After first shift operation: Tutorials After second shift operation: Point After third shift operation: Hyderabad After fourth shift operation: India The deque after removing all elements one by one: Ds\Deque Object ( )