Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds Deque::unshift() Function



The PHP Ds\Deque::unshift() function is used to add a value to the front of the deque. This operation shifts existing elements to make space for the new value.

Using this function you can add multiple values at a time in the same order that they are passed.

Syntax

Following is the syntax of the PHP Ds\Deque::unshift() function −

public Ds\Deque::unshift(mixed $values = ?): void

Parameters

This function accepts the following parameter −

  • values − The value need to be added to the front of the deque.

Return value

This function does not return any values.

Example 1

The following is the basic example of the PHP Ds\Deque::unshift() function −

<?php
   $deque = new \Ds\Deque([12, 24,36,48,60,72]);
   echo "The deque elements are: \n";
   print_r($deque);
   $val = 72;
   echo "The given value: ".$val;
   $deque->unshift(72);
   echo "\nThe deque after adding new element: \n";
   print_r($deque);
?>

Output

The above program produces the following output −

The deque elements are:
Ds\Deque Object
(
    [0] => 12
    [1] => 24
    [2] => 36
    [3] => 48
    [4] => 60
    [5] => 72
)
The given value: 72
The deque after adding new element:
Ds\Deque Object
(
    [0] => 72
    [1] => 12
    [2] => 24
    [3] => 36
    [4] => 48
    [5] => 60
    [6] => 72
)

Example 2

Following is another example of the PHP Ds\Deque::unshift() function. We use this function to add values 'p' and 'g' to the front of this deque (['g', 'j', 'p', 'q', 'y']) −

<?php
   $deque = new \Ds\Deque(['g', 'j', 'p', 'q', 'y']);
   echo "The deque elements are: \n";
   print_r($deque);
   $val1 = 'p';
   $val2 = 'g';
   echo "The given values are: ".$val1.", ".$val2;
   #using unshift() function
   $deque->unshift($val1);
   $deque->unshift($val2);
   echo "\nThe deque after adding new values: \n";
   print_r($deque);
?>

Output

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

The deque elements are:
Ds\Deque Object
(
    [0] => g
    [1] => j
    [2] => p
    [3] => q
    [4] => y
)
The given values are: p, g
The deque after adding new values:
Ds\Deque Object
(
    [0] => g
    [1] => p
    [2] => g
    [3] => j
    [4] => p
    [5] => q
    [6] => y
)
Advertisements