Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there the equivent of a Java Set in php? [duplicate]

Is there the equivalent of a Java Set in php?

(meaning a collection that can't contain the same element twice)

like image 899
leeand00 Avatar asked Jan 12 '10 18:01

leeand00


People also ask

Is there a Hashmap in PHP?

HashMaps is a custom PHP Library that allows support for Java HashMaps in PHP.

When to use a Set in Java?

As the name implies, a set in Java is used to create a mathematical set. Since the set extends the collection interface, it does not allow duplicate elements. In the hierarchy, NavigableSet and SortedSet are the two interfaces that extend set in Java.

When to use Set Over List?

The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates. List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.


3 Answers

You could just use an array and put the data you want in the key because keys can't be duplicated.

like image 133
cletus Avatar answered Sep 22 '22 12:09

cletus


You can use a standard PHP array of values, and pass it through array_unique function:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Outputs:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}
like image 20
Ivan Krechetov Avatar answered Sep 21 '22 12:09

Ivan Krechetov


SplObjectStorage is the closest thing.

$storage = new SplObjectStorage;
$obj1    = new StdClass;

$storage->attach($obj1);
$storage->attach($obj1); // not attached
echo $storage->count();  // 1

$obj2    = new StdClass; // different instance
$obj3    = clone($obj2); // different instance

$storage->attach($obj2);
$storage->attach($obj3);    
echo $storage->count();  // 3

As the name implies, this is only working with objects though. If you'd want to use this with scalar types, you'd have to use the new Spl Types as a replacement, as well as the Spl Data Structures and ArrayObject for Array replacements.

like image 29
Gordon Avatar answered Sep 18 '22 12:09

Gordon