Backend Development 4 min read

Using PHP array_unique() to Remove Duplicate Elements

This article explains the PHP array_unique() function, its syntax and parameters, demonstrates how to remove duplicate values from arrays with practical code examples, and shows how the optional $sort_flag argument can affect sorting behavior.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP array_unique() to Remove Duplicate Elements

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

The function signature is:

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

Parameters:

$array : the input array that needs deduplication.

$sort_flag : optional, determines how the array elements are sorted during the deduplication process.

Return value: an array containing only the first occurrence of each value.

Example 1 demonstrates removing duplicates from a fruit list:

<?php
$fruits = array("apple", "banana", "orange", "apple", "melon", "banana");
$uniqueFruits = array_unique($fruits);
print_r($uniqueFruits);
?>

The output shows that "apple" and "banana" appear only once while other elements remain unchanged:

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

The optional $sort_flag can be set to SORT_STRING (default) to treat elements as strings and sort them lexicographically, or SORT_REGULAR for regular comparison.

Example 2 shows using $sort_flag with SORT_STRING on a numeric array:

<?php
$numbers = array(1, 3, 5, 2, 5, 4);
$uniqueNumbers = array_unique($numbers, SORT_STRING);
print_r($uniqueNumbers);
?>

The result is a deduplicated array sorted in ascending order:

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

In summary, array_unique() is a convenient PHP function for quickly eliminating duplicate entries from arrays, and by specifying the $sort_flag you can control the sorting behavior during deduplication, which simplifies array handling and improves code efficiency.

BackendPHPSortingDuplicate 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.