Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP 5.x have some kind of HashSet or Set Class?

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.

like image 956
Pascal Klein Avatar asked Jan 19 '11 01:01

Pascal Klein


People also ask

Does PHP have Set?

A PHP array provides both a List and a HashMap , but not a Set .

Is HashSet a class or interface?

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.

What is the difference between Set and HashSet?

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.

What is difference between HashMap and HashSet?

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.


2 Answers

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.

like image 173
Artefacto Avatar answered Sep 16 '22 14:09

Artefacto


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 :)

like image 20
karl Avatar answered Sep 17 '22 14:09

karl