The add
method of the Set data structure can be used to add values to the Set.
A set is a collection of unique values. In
Ds\Set
we can store any type of value including objects. The insertion order of the element is preserved.
By default, the data structures are not installed in PHP, we can install them by following these instructions on php.net.
public Ds\Set::add(mixed ...$values): void
This method takes the values to be added as an argument.
The values which are not already present in the Ds\Set
will be added to the set.
<?php$set = new \Ds\Set();$set->add(1,2);var_dump($set);// 1 is already present in the set so it will not be added$set->add(1);var_dump($set);// int 1 is not equal to string "1" so "1" will be added to the set$set->add("1");var_dump($set);?>
object(Ds\Set)#3 (2) {
[0]=>
int(1)
[1]=>
int(2)
}
object(Ds\Set)#3 (2) {
[0]=>
int(1)
[1]=>
int(2)
}
object(Ds\Set)#3 (3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
string(1) "1"
}
In the code above, we created an object of type Set and added elements using the add
method. We also tried adding duplicate values, but in the set, duplicate values were not added.