Remove Duplicate Values from PHP Array with array_unique
This article explains how to use the PHP array_unique()
function to selectively remove duplicate values from an array. You will
learn the basic syntax of the function, how to use different sorting
flags to control how duplicates are compared, and how to handle
duplicates in both simple and multidimensional arrays.
Basic Usage of array_unique()
The array_unique() function takes an input array and
returns a new array with duplicate values removed. By default, it keeps
the first encountered key for each unique value and discards the
subsequent duplicates.
$fruits = ["apple", "banana", "apple", "cherry", "banana"];
$unique_fruits = array_unique($fruits);
print_r($unique_fruits);Output:
Array
(
[0] => apple
[1] => banana
[3] => cherry
)
Note: The keys are preserved. If you want to re-index the array
keys starting from 0, wrap the result in
array_values().
$reindexed = array_values(array_unique($fruits));Selective Removal Using Flags
The behavior of array_unique() can be customized using
its second parameter, $flags. These flags determine how
array elements are compared:
SORT_STRING(Default): Compares items as strings.SORT_REGULAR: Compares items normally without changing types (e.g., integer1and string"1"will be treated as different).SORT_NUMERIC: Compares items numerically.SORT_LOCALE_STRING: Compares items as strings, based on the current locale.
Example: String vs. Regular Comparison
If you have an array with mixed data types, the flag you choose changes what is considered a duplicate.
$data = [1, "1", 2, "2"];
// Using SORT_STRING (default) treats 1 and "1" as duplicates
$string_compare = array_unique($data, SORT_STRING);
// Output: [1, 2]
// Using SORT_REGULAR preserves the data types
$regular_compare = array_unique($data, SORT_REGULAR);
// Output: [1, "1", 2, "2"]Removing Duplicates from Multidimensional Arrays
The array_unique() function does not work directly on
multidimensional arrays (arrays containing other arrays) because it
cannot convert inner arrays to strings by default. To selectively remove
duplicates based on a specific key in a multidimensional array, you can
combine array_unique() with
array_column().
For example, to remove duplicate users based on their
email address:
$users = [
["id" => 1, "name" => "Alice", "email" => "alice@example.com"],
["id" => 2, "name" => "Bob", "email" => "bob@example.com"],
["id" => 3, "name" => "Alice Dup", "email" => "alice@example.com"],
];
// Extract the column you want to make unique
$emails = array_column($users, 'email');
// Find the unique values and get their original keys
$unique_keys = array_keys(array_unique($emails));
// Filter the original array using the unique keys
$unique_users = array_intersect_key($users, array_flip($unique_keys));
print_r(array_values($unique_users));Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[email] => alice@example.com
)
[1] => Array
(
[id] => 2
[name] => Bob
[email] => bob@example.com
)
)