I'm used to Java where I have HashSets
, ArrayLists
and other Collections
. But I'm workting on a PHP project right now.
I need to create a set, fill that set with objects (Strings in this case), but the Set can only contain each object once. In addition I want to remove a certain object in the end from this set if it exists. This would be pretty easy with the Java collection classes. But how can I implement that in PHP?
Are there any methods of array()
that I am missing? I'm using PHP 5.3.
A PHP array provides both a List and a HashMap , but not a Set .
Class HashSet<E> This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
A Set is a generic set of values with no duplicate elements. A TreeSet is a set where the elements are sorted. A HashSet is a set where the elements are not sorted or ordered.
Hashmap is the implementation of Map interface. Hashset on other hand is the implementation of set interface. Hashmap internally do not implements hashset or any set for its implementation. Hashset internally uses Hashmap for its implementation.
If it's just strings, you can use arrays as sets:
$arr['str1'] = null;
$arr['str2'] = null;
$arr['str1'] = null;
print_r(array_keys($arr));
You only potential problem is that numeric strings are implicitly converted to integers, if possible. But that's usually not a problem in PHP because the type doesn't matter in most circumstances.
PHP documentation says:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
So maybee(!) you don't need a HashSet, because a normal array is implemented already as a kind of an optimized index structure :)
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