开发者

Does PHP 5.x have some kind of HashSet or Set Class?

开发者 https://www.devze.com 2023-02-05 15:23 出处:网络
I\'m used to Java where I have HashSets, ArrayLists and ot开发者_运维百科her Collections. But I\'m workting on a PHP project right now.

I'm used to Java where I have HashSets, ArrayLists and ot开发者_运维百科her Collections. But I'm workting on a PHP project right now.

I need to create a set, fill that set with objects (Strings in this case), but the Set can only contain each object once. In addition I want to remove a certain object in the end from this set if it exists. This would be pretty easy with the Java collection classes. But how can I implement that in PHP?

Are there any methods of array() that I am missing? I'm using PHP 5.3.


If it's just strings, you can use arrays as sets:

$arr['str1'] = null;
$arr['str2'] = null;
$arr['str1'] = null;

print_r(array_keys($arr));

You only potential problem is that numeric strings are implicitly converted to integers, if possible. But that's usually not a problem in PHP because the type doesn't matter in most circumstances.


PHP documentation says:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

So maybee(!) you don't need a HashSet, because a normal array is implemented already as a kind of an optimized index structure :)


I'm not exactly sure, but I think SplObjectStorage does what you want:

http://php.net/manual/en/class.splobjectstorage.php

Oh, and strings are not objects. So you can just do this:

$foo['bar'] = true;

and the array will work as a way to uniquely store the strings.


$values = array(1, 3, 6, 4, 3, 3, 7, 1);
$hashset = array();
foreach ($values as $value){
    if (!array_key_exists($value, $hashset)){
        echo $value." ";
        $hashset[$value] = true;
    }
}

Prints: 1 3 6 4 7

0

精彩评论

暂无评论...
验证码 换一张
取 消