I'm looking for a simple way to create an array in php that will not allow duplicate entries, but allows for easy combining of other sets or arrays.
I'm mostly interested in whether such a feature exists in the language because writing my own wouldn't be difficult. I just don't want to if I don't need to.
In Laravel there is a method
unique
inCollection
class that may be helpful. From Laravel documentation:Just an idea, if you use the array keys instead of values, you'll be sure there are no duplicates, also this allows for easy merging of two "sets".
I also had this problem and so have written a Class: https://github.com/jakewhiteley/php-set-object
As suggested, it does extend and ArrayObject and allow native-feeling insertion/iteration/removal of values, but without using
array_unique()
anywhere.Implementation is based on the MDN JS Docs for Sets in EMCA 6 JavaScript.
You can use array_combine for removing duplicates
The answer is no, there is not a native set solution inside PHP. There is a
Set
data structure, but that is not baseline PHP.There is a convention for implementing sets using maps (i.e. associative arrays) in any language. And for PHP you should use
true
as the bottom value.