PHP - Ds Set add() 函式



PHP 的Ds\Set::add()函式用於將指定的值新增到當前集合中。您可以同時新增多種不同型別的值。例如,可以同時將值1、2、'a'、'b'、“Hello”和“World”新增到集合中。

語法

以下是PHP Ds\Set::add()函式的語法:

public void Ds\Set::add([ mixed $...values ] )

引數

此函式接受一個名為“values”的引數,該引數包含多個值:

  • values - 需要新增到集合中的值。

返回值

此函式不返回值。

示例1

以下是PHP Ds\Set::add()函式的基本示例。

<?php
   $set = new \Ds\Set();
   echo "The set before adding any value: \n";
   print_r($set);
   #using add() function
   $set->add(100);
   $set->add('a');
   $set->add(101);
   echo "The set after adding values to it: \n";
   print_r($set);
?>

輸出

上述程式產生以下輸出:

The set before adding any value:
Ds\Set Object
(
)
The set after adding values to it:
Ds\Set Object
(
    [0] => 100
    [1] => a
    [2] => 101
)

示例2

以下是PHP Ds\Set::add()函式的另一個示例。我們使用此函式將指定的值“welcome”、“hello”和“hi”新增到此集合(["Hey"])中。

<?php
   $set = new \Ds\Set(["Hey"]);
   echo "The set before adding any value: \n";
   print_r($set);
   $v1 = "welcome";
   $v2 = "hello";
   $v3 = "hi";
   echo "Values need to be added: ".$v1.", ".$v2.", ".$v3;
   $set->add($v1);
   $set->add($v2);
   $set->add($v3);
   echo "\nThe set after adding values to it: \n";
   print_r($set); 
?>

輸出

執行上述程式後,將生成以下輸出:

The set before adding any value:
Ds\Set Object
(
    [0] => Hey
)
Values need to be added: welcome, hello, hi
The set after adding values to it:
Ds\Set Object
(
    [0] => Hey
    [1] => welcome
    [2] => hello
    [3] => hi
)

示例3

一次新增多種不同型別的值。

在下面的示例中,我們使用PHP Ds\Set::add()函式一次性將多種不同型別的值8、64、“eight”和'j'新增到當前集合中。

<?php
   $set = new \Ds\Set();
   echo "The set before adding any value: \n";
   print_r($set);
   $set->add(8, 64, "eight", 'j');
   echo "The set after adding values to it: \n";
   print_r($set);
?>

輸出

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

The set before adding any value:
Ds\Set Object
(
)
The set after adding values to it:
Ds\Set Object
(
    [0] => 8
    [1] => 64
    [2] => eight
    [3] => j
)
php_function_reference.htm
廣告