PHP - Ds Vector::unshift() 函式



PHP 的 Ds\Vector::unshift() 函式用於將值新增到向量的開頭,並將所有現有值向前移動以騰出空間以容納新值。

此函式允許您一次將多個值新增到向量的開頭。它不返回任何內容,但會修改原始向量。

Ds\Vector 類提供了另一個名為 insert() 的函式,允許您在指定的索引處新增值,如果索引為 0,則元素始終會新增到向量的開頭。

語法

以下是 PHP Ds\Vector::unshift() 函式的語法:

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

引數

以下是此函式的引數:

  • values - 需要新增的單個或多個值。

返回值

此函式不返回任何值。

示例 1

以下程式演示了 PHP Ds\Vector::unshift() 函式的用法:

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4]); 
   echo "The original vector: \n"; 
   print_r($vector);
   $value = 5;
   echo "The given value: ".$value;
   echo "\nThe vector elements after inserting new element: \n";
   #using unshift() function
   $vector->unshift($value); 
   print_r($vector);
?>

輸出

以上程式產生以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
The given value: 5
The vector elements after inserting new element:
Ds\Vector Object
(
    [0] => 5
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
)

示例 2

我們正在一次將多個值新增到向量的開頭。

以下是另一個 PHP Ds\Vector::unshift() 函式的示例。我們使用此函式將指定的值新增到此向量的開頭:

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point"]);
   echo "The original vector: \n"; 
   print_r($vector); 
   $val1 = "India";
   $val2 = "Tutorix";
   echo "The given values are: ".$val1.", ".$val2;
   echo "\nThe vector elements after inserting new elements: \n";
   $vector->unshift($val1, $val2);
   print_r($vector); 
?>

輸出

執行上述程式後,將顯示以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
)
The given values are: India, Tutorix
The vector elements after inserting new elements:
Ds\Vector Object
(
    [0] => India
    [1] => Tutorix
    [2] => Tutorials
    [3] => Point
)
php_function_reference.htm
廣告