views:

96

answers:

3

Is there the equivalent of a Java Set in php?

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

+2  A: 

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.

Gordon
+7  A: 

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

cletus
+3  A: 

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"
}
Ivan Krechetov