Backend Development 4 min read

Using PHP's array_unique() Function to Remove Duplicate Array Elements

This article explains PHP's array_unique() function, detailing its syntax, parameters, and return value, and provides clear examples showing how to remove duplicate elements from arrays and optionally sort them using the $sort_flag parameter.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_unique() Function to Remove Duplicate Array Elements

In PHP programming, the array_unique() function is commonly used to remove duplicate values from an array and return a new array containing only unique elements.

The function signature is:

array_unique(array $array, int $sort_flag = SORT_STRING): array

Parameters:

$array : the input array that may contain duplicate values.

$sort_flag (optional): determines how the array elements are sorted during the uniqueness check. The default is SORT_STRING , which treats elements as strings and sorts them lexicographically. Another option is SORT_REGULAR , which uses regular comparison.

The function returns a new array with duplicate entries removed, preserving the first occurrence of each value.

Example 1 demonstrates basic usage:

<?php
// Define an array with duplicate elements
$fruits = array("apple", "banana", "orange", "apple", "melon", "banana");
// Remove duplicates
$uniqueFruits = array_unique($fruits);
// Output the result
print_r($uniqueFruits);

Running this code produces:

Array
(
[0] => apple
[1] => banana
[2] => orange
[4] => melon
)

As shown, the duplicate "apple" and "banana" entries are removed, while the other elements remain unchanged.

Example 2 shows how to use the optional $sort_flag parameter to sort the unique values as strings:

<?php
$numbers = array(1, 3, 5, 2, 5, 4);
// Remove duplicates and sort as strings
$uniqueNumbers = array_unique($numbers, SORT_STRING);
// Output the result
print_r($uniqueNumbers);

The output is:

Array
(
[0] => 1
[1] => 2
[2] => 3
[4] => 4
[5] => 5
)

By specifying SORT_STRING , the numeric values are treated as strings and sorted in ascending order after duplicates are removed.

In summary, array_unique() is a convenient PHP function for deduplicating arrays, and the optional $sort_flag allows developers to control the sorting behavior of the resulting unique array, enhancing code efficiency in backend development.

backendPHPsortingarraysDuplicate Removalarray_unique
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.