I'm relatively new to php and having a hard time figuring out the right data structure to use. Let's say I have a class FooBar with equals()
and hashCode()
properly implemented. What kind of collection in php (if there is any at all) that most resembles Java's hashSet? I need a collection of objects without duplicates. Someone's suggested using array and the function array_key_exists
, but I was just wondering if there's another way to do this?
-
Arrays would be the way to go. You can use PHP's array_unique function to extract an array without duplicates, or use array_key_exists before inserting.– Connor PeetCommented May 16, 2012 at 7:02
2 Answers
Starting from release 5.2 Php offers SplObjectStorage, that offers functionalities of Java's Set:
- Cares about uniqueness (same object can't be added twice)
- Easy to iterate through the collection
- Easy to check existence of an object in the collection
Check http://technosophos.com/content/set-objects-php-arrays-vs-splobjectstorage for example of use
There are few Data structures available in the PHP programming language provided by the Standard PHP Library (SPL). Although they are nothing when compared with the Java Collections Framework implementations, sometimes they can be very useful by providing a more advanced functionality than that of the arrays. You can find the documentation of the available Data structures here.
The most HashSet-like Data structure in PHP would be SplObjectStorage.
From the documentation:
The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects.
Objects in PHP don't implement the equals()
and the hashCode()
methods. Uniqueness of objects is determined by the value returned from the spl_object_hash()
function. The same value is used by the SplObjectStorage
class to uniquely identify the objects it contains. The SplObjectStorage::getHash($object)
method can be used to retrieve the identifier of an object contained in the SplObjectStorage
collection.