6

How to implement set theory operations in pure php?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Thomas Vincent
  • 248
  • 2
  • 12

2 Answers2

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
  • 3
    It'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:

http://jamietalbot.com/2010/02/04/set-operations-in-php/

http://oreilly.com/catalog/progphp/chapter/ch05.html

Strae
  • 18,807
  • 29
  • 92
  • 131