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?
HashSets are excellent when you want to store large number of collections. Because, the basic add, remove, contains operations are constant time operations. In other words, putting an object in an empty set is same as putting it in a set having n records.
The equals() method of java. util. HashSet class is used verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains same elements, irrespective of order.
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.
Starting from release 5.2 Php offers SplObjectStorage, that offers functionalities of Java's Set:
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.
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