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

Pascal Klein picture Pascal Klein · Jan 19, 2011 · Viewed 13.4k times · Source

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.

Answer

Artefacto picture Artefacto · Nov 19, 2011

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.