6

Is there the equivalent of a Java Set in php?

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

leeand00
  • 25,510
  • 39
  • 140
  • 297

3 Answers3

11

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

cletus
  • 616,129
  • 168
  • 910
  • 942
6

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
  • 18,802
  • 8
  • 49
  • 60
5

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
  • 312,688
  • 75
  • 539
  • 559