Jesse Jashinsky
Jesse Jashinsky

Reputation: 10663

Does PHP have a Set data structure?

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.

Upvotes: 21

Views: 34134

Answers (7)

okdewit
okdewit

Reputation: 2566

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])

Upvotes: 14

Acsor
Acsor

Reputation: 1061

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.

Upvotes: 4

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

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]);

Upvotes: 3

VolkerK
VolkerK

Reputation: 96159

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+).

Upvotes: 5

Randy the Dev
Randy the Dev

Reputation: 26720

Just use a php array, there's no such thing as a 'fixed size' array in PHP so you should be fine with them.

Upvotes: 2

Andy Lester
Andy Lester

Reputation: 93666

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.

Upvotes: 3

Mike Dinescu
Mike Dinescu

Reputation: 55720

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).

Upvotes: 8

Related Questions