PHP - Ds Set::diff() 函式



PHP 的 Ds\Set::diff() 函式建立一個新的集合,其中包含另一個集合中不存在的所有值。

如果第一個集合中的值也存在於第二個集合中,則此函式返回一個 empty() 集合。例如,set1 = ([1, 2]),set2 = ([1, 2, 3]),因此 set1->diff(set2) 將為空 (),因為 set1 的值 12 存在於 set2 中。

語法

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

public Ds\Set Ds\Set::diff( Ds\Set $set )

引數

以下是此函式的引數:

  • set - 包含要排除的值的另一個集合。

返回值

此函式返回一個新集合,其中包含不在另一個集合中的所有值。

示例 1

以下程式演示了 Ds\Set::diff() 函式的使用:

<?php  
   $set1 = new \Ds\Set([1, 2, 3]);
   echo "The set1 elements are: \n";
   print_r($set1);   
   $set2 = new \Ds\Set([3, 4, 5]);
   echo "The set2 elements are: \n";
   print_r($set2);   
   echo("The difference of set1 and set2: \n");  
   print_r($set1->diff($set2)); 
?>

輸出

上述程式生成以下輸出:

The set1 elements are:
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
The set2 elements are:
Ds\Set Object
(
    [0] => 3
    [1] => 4
    [2] => 5
)
The difference of set1 and set2:
Ds\Set Object
(
    [0] => 1
    [1] => 2
)

示例 2

如果第一個集合的所有元素也存在於第二個集合中,則此函式將返回一個 empty () 集合。

以下是 PHP Ds\Set::diff() 函式的另一個示例。我們使用此函式檢索一個新集合,其中包含此集合 ([10, 20, 30, 40, 50]) 中不存在的所有元素:

<?php  
   $set1 = new \Ds\Set([10, 20, 30]);
   echo "The set1 elements are: \n";
   print_r($set1);   
   $set2 = new \Ds\Set([10, 20, 30, 40, 50]);
   echo "The set2 elements are: \n";
   print_r($set2);   
   echo("The difference of set1 and set2: \n");  
   print_r($set1->diff($set2)); 
?>

輸出

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

The set1 elements are:
Ds\Set Object
(
    [0] => 10
    [1] => 20
    [2] => 30
)
The set2 elements are:
Ds\Set Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The difference of set1 and set2:
Ds\Set Object
(
)

示例 3

如果第一個集合的所有元素都不存在於第二個集合中,則 PHP Ds\Set::diff() 函式將返回一個新集合,其中包含另一個集合中不存在的所有值:

<?php  
   $set1 = new \Ds\Set(["Tutorials", "Point", "India"]);
   echo "The set1 elements are: \n";
   print_r($set1);   
   $set2 = new \Ds\Set(["Tutorix", "India"]);
   echo "The set2 elements are: \n";
   print_r($set2);   
   echo("The difference of set1 and set2: \n");  
   print_r($set1->diff($set2)); 
?>

輸出

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

The set1 elements are:
Ds\Set Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The set2 elements are:
Ds\Set Object
(
    [0] => Tutorix
    [1] => India
)
The difference of set1 and set2:
Ds\Set Object
(
    [0] => Tutorials
    [1] => Point
)
php_function_reference.htm
廣告