Understanding array_unique() in PHP

The array_unique function in PHP removes duplicate values from an array. It returns a new array containing only the unique values, preserving the original keys.

Preserves Keys:

By default, array_unique() preserves the keys of the original array. This means that the order of the elements is maintained.

Optional Flags:

The function accepts an optional second parameter, $flags, which can be used to customize the comparison of elements. Here are some commonly used flags:

  • SORT_STRING: This flag performs a string comparison of the elements.
  • SORT_NUMERIC: This flag performs a numeric comparison of the elements.
  • SORT_REGULAR: This flag performs a regular expression comparison of the elements.
Additional Notes:
  • array_unique() is case-sensitive by default.
  • If two or more elements compare equal, the first occurrence will be kept and the others will be removed.
  • You can use the array_values() function to get an array with only the values, without the keys.
Example 1: Removing Duplicate Students

 
$students = array(
  array('id' => 1, 'name' => 'John'),
  array('id' => 2, 'name' => 'Mary'),
  array('id' => 3, 'name' => 'John'),
  array('id' => 4, 'name' => 'Alice'),
  array('id' => 5, 'name' => 'Mary'),
);
 
$unique_students = array_unique($students, SORT_REGULAR);
 
print_r($unique_students);
 
 

This example defines a students array containing five elements, some with duplicate names. Calling array_unique removes the duplicate "John" and "Mary" entries, resulting in:

 

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John
        )
    [1] => Array
        (
            [id] => 2
            [name] => Mary
        )
    [3] => Array
        (
            [id] => 4
            [name] => Alice
        )
)