How to implement set theory operations in pure php?
Asked
Active
Viewed 2,904 times
2 Answers
10
Which operations are you looking for? What are you trying to accomplish?
In PHP an array is (imperfectly) analogous to a set, and PHP has array_intersect
, array_merge
(union), and array_diff
(complement) functions built in. There's also array_uintersect
and array_udiff
for handling complex objects whose comparisons are not so straightforward.
Is there further functionality you need?

Jordan Running
- 102,619
- 17
- 182
- 182
-
3It's worth noting that array_merge isn't a true union according to set theory. You have to do array_merge then array_unique on the result otherwise you can end up with duplicates. The link that Strae provided in his answer to [Programming PHP](http://oreilly.com/catalog/progphp/chapter/ch05.html) demonstrates this. – David Kanenwisher Jun 05 '14 at 20:35
2
Probably you'll already saw those links:

Strae
- 18,807
- 29
- 92
- 131
-
For comparing non-scalar values, such as stdClass objects and other data types. – Justin Mitchell Jan 28 '16 at 00:57
-
https://web.archive.org/web/20201021103045/http://jamietalbot.com/2010/02/04/set-operations-in-php/ – Serhii Smirnov Nov 21 '22 at 12:48
-
https://web.archive.org/web/20080905054045/http://oreilly.com/catalog/progphp/chapter/ch05.html – Serhii Smirnov Nov 21 '22 at 12:49