问题
I'm new to PHP, and I can't figure out this basic question. Does PHP have some sort of set or list object? Something like an array, but with the ability to dynamically add or remove any number of objects from it.
回答1:
Yes, you could use the array object and the array functions.
Basically, you could dynamically grow an array using the array_push function, or the $arrayName[] = ... notation (where arrayName is the name of your array).
回答2:
Since you've mentioned a "Set object" in the question's title (i.e. if you need the objects not to be repeated within the set) , take a look at SplObjectStorage (php 5.3+).
回答3:
If you are looking for a Set data structure without repeated elements, it seems that as of PHP 7 the SPL adds support for a Set data structure.
回答4:
You can use Set from Nspl. It supports basic set operations which take other sets, arrays and traversable objects as arguments:
$set = set(1, 2);
$set->add('hello');
$set[] = 'world';
$set->delete('hello');
$array = [1, 2, 3];
$intersection = $set->intersection($array);
$anotherSet = Set::fromArray([1, 2, 3]);
$difference = $set->difference($anotherSet);
$iterator = new \ArrayIterator([1, 2, 3]);
$union = $set->union($iterator);
$isSubset = $set->isSubset([1, 2, 'hello', 'world']);
$isSuperset = $set->isSuperset([1, 2]);
回答5:
PHP's arrays like a mashup of ordered arrays indexed by a number, and a hash lookup table. You can look up any element by a string index, but elements also have a defined order.
回答6:
Just use a php array, there's no such thing as a 'fixed size' array in PHP so you should be fine with them.
回答7:
The PHP7+ answer: Use the official PHP-DS extension. It's much more efficient than hacky solutions using arrays. Sets come with some limitations, but most of the typical operations on them are much faster and provide a better interface.
https://www.php.net/manual/en/book.ds.php
<?php
use Ds\Set;
$numbers = new Set([1, 2, 3]);
$numbers->sum();
$numbers->diff(new Set([2, 3, 4]))
->union(new Set([3, 4, 5]))
->remove(...[3, 4])
来源:https://stackoverflow.com/questions/3764800/does-php-have-a-set-data-structure