Is there the equivalent of a Java Set in php?
(meaning a collection that can't contain the same element twice)
HashMaps is a custom PHP Library that allows support for Java HashMaps in PHP.
As the name implies, a set in Java is used to create a mathematical set. Since the set extends the collection interface, it does not allow duplicate elements. In the hierarchy, NavigableSet and SortedSet are the two interfaces that extend set in Java.
The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates. List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.
You could just use an array and put the data you want in the key because keys can't be duplicated.
You can use a standard PHP array of values, and pass it through array_unique function:
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
Outputs:
array(2) {
[0] => int(4)
[2] => string(1) "3"
}
SplObjectStorage is the closest thing.
$storage = new SplObjectStorage;
$obj1 = new StdClass;
$storage->attach($obj1);
$storage->attach($obj1); // not attached
echo $storage->count(); // 1
$obj2 = new StdClass; // different instance
$obj3 = clone($obj2); // different instance
$storage->attach($obj2);
$storage->attach($obj3);
echo $storage->count(); // 3
As the name implies, this is only working with objects though. If you'd want to use this with scalar types, you'd have to use the new Spl Types as a replacement, as well as the Spl Data Structures and ArrayObject for Array replacements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With