How to push large set of strings to SplObjectStorage in PHP and if string exist not to push

StackOverflow https://stackoverflow.com/questions/23368291

  •  12-07-2023
  •  | 
  •  

Question

Basically what I need is to push a large set of strings to SplObjectStorage and if each string doesn't exist do some kind of action, if it does exist do other action.

$o1->id = '11111';
$s->attach($o1);
$o1->id = '22222';
$s->attach($o1);

I only get 22222 in the object, or it overwrites the object. I need to get both, And if they match just one of them. I need to get distinct values of my strings

Was it helpful?

Solution

The problem here is that you're updating the same object, and the object itself is not added twice.

If you're only working with strings, it would be more efficient to use an array:

$array = [];

if (!isset($array['11111'])) {
    $array['11111'] = true;
}
// etc.

Afterwards, you can use array_keys() to fetch all unique values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top