在php中是否有类似于Java Set的等效物?

6

在php中是否有类似于Java Set的等效集合?

(意思是一个不能包含相同元素两次的集合)

3个回答

11

你可以使用数组,将你想要的数据放入键中,因为键是不可重复的。


6

您可以使用标准的PHP值数组,并通过array_unique函数进行传递:

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

输出:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

5

SplObjectStorage 是最接近的东西。

$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

如其名,这只能用于对象。如果你想要将其用于标量类型,你需要使用新的Spl Types替代,同时使用Spl Data StructuresArrayObject来替换数组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接