Reputation: 38005
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.
Upvotes: 79
Views: 61936
Reputation: 1478
I needed a Set in a project to save unique objects. To do that you can use spl_object_id
or spl_object_hash
.
$mySet = [];
$mySet[spl_object_id($object)] = $object;
Note: When using spl_object_id
dont't merge arrays with array_merge
or [...$array1, ...$array2]
because those reorder integer keys. Use $array1 + $array2
to keep existing keys.
This way of adding objects to the arrays could be wrapped in a class to make sure only objects are added and all objects are added using spl_object_id
.
Upvotes: 0
Reputation: 2390
The Set class.
https://www.php.net/manual/en/class.ds-set.php
Don't know when will it come out.
Upvotes: 4
Reputation: 39253
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.
<?php
$left = [1=>true, 5=>true, 7=>true];
$right = [6=>true, 7=>true, 8=>true, 9=>true];
$union = $left + $right;
$intersection = array_intersect_assoc($left, $right);
var_dump($left, $right, $union, $intersection);
Upvotes: 18
Reputation: 6689
In Laravel there is a method unique
in Collection
class that may be helpful. From Laravel documentation:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
Upvotes: 1
Reputation: 5912
You can use array_combine for removing duplicates
$cars = array("Volvo", "BMW", "Toyota");
array_push($cars,"BMW");
$map = array_combine($cars, $cars);
Upvotes: 4
Reputation: 505
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.
Upvotes: 2
Reputation: 7743
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".
$set1 = array ('a' => 1, 'b' => 1, );
$set2 = array ('b' => 1, 'c' => 1, );
$union = $set1 + $set2;
Upvotes: 86