Does PHP have a Set data structure?

Viewed 27177

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.

7 Answers

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