PHP array_unique() function
The array_unique()
function in PHP is used to remove duplicate values from an array. This function compares the values in the array and returns a new array containing only the unique values. It is particularly useful when you want to ensure that your array contains distinct elements, eliminating redundancy.
Syntax:
Parameters:
- $array: The input array from which to remove duplicate values.
- $sort_flags: (Optional) A flag that can be used to specify how the values should be compared. The default is
SORT_STRING
, which treats values as strings. Other options include:SORT_REGULAR
: Compare items normally (default behavior).SORT_NUMERIC
: Compare items numerically.SORT_STRING
: Compare items as strings.SORT_LOCALE_STRING
: Compare items as strings, based on the current locale.
Return Value:
- Returns a new array containing unique values from the input array. The keys of the original array are preserved.
Example 1: Basic Usage
In this example, we demonstrate how to use array_unique()
to remove duplicate values.
Output:
In this case, the duplicate values 2
and 4
are removed, leaving the unique elements.
Example 2: Preserving Keys
The keys of the original array are preserved in the new array.
Output:
Here, the key 2
associated with the second occurrence of 'apple'
is not included in the result, but the keys of other unique values are preserved.
Example 3: Working with Strings
You can also use array_unique()
with arrays of strings.
Output:
In this example, the duplicate string values are removed, resulting in an array of unique strings.
Example 4: Using Sort Flags
You can specify a sort flag to compare values in a specific way. For example, using SORT_NUMERIC
can be useful when you have numeric strings.
Output:
Here, the string '1'
and the integer 1
are considered equal when compared numerically, so only one instance is kept.
Practical Usage:
array_unique()
is useful for:- Cleaning up data by removing duplicates.
- Ensuring that lists of items (such as product IDs, names, etc.) contain only distinct entries.
- Preparing data for further processing or analysis.
Summary:
array_unique($array, $sort_flags)
removes duplicate values from an array and returns a new array containing only unique values.- The keys from the original array are preserved in the new array.
- This function is a simple and effective way to handle duplicates in arrays in PHP.