Does PHP have a Set data structure?

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

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.


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


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

Tags:

Php

Set