Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 61 / 68

Set Operations with Arrays (Union, Intersection, Difference)

In this lesson you will learn to treat PHP arrays as sets and compute unions, intersections, and differences. This is for anyone searching for "PHP set operations how to use".

PHP has no dedicated Set type, but array_unique(), array_intersect(), and array_diff() let you treat arrays as sets and compute the union, intersection, and difference.

The sample code computes the union by combining array_merge() with array_unique(), the intersection with array_intersect(), and the difference with array_diff(). Notice how each of the three operations has its own dedicated function.

A common stumbling block for beginners is that the result keeps the original keys. Watch how sort() both orders the values and renumbers the keys for a tidier display.

It is a useful way of thinking for real data work, such as finding the users common to two groups. The ideas behind intersection and difference also carry over to understanding join operations in SQL.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)