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

Using an Array as a Set (Duplicate-Free Data)

In this lesson you will learn how to treat a PHP array as a set so you can strip duplicates efficiently. This is for anyone searching for "PHP array_unique how to use".

PHP has no dedicated Set type, but array_unique() removes duplicates from an array. It is the standard technique when you want a box that refuses to hold the same value twice.

The sample code builds a duplicate-free array from $nums with array_unique($nums), then renumbers the keys with array_values(). Notice how array_values tidies the keys into a sequence starting at 0.

A common stumbling block for beginners is that array_unique() keeps the original keys. On its own it leaves gaps in the numbering, so you need array_values() as well if you want a clean sequence.

It runs faster than checking the array one element at a time and is a data-tidying technique used constantly in practice - for example removing duplicate tags selected in a form.

๐Ÿ“– 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)