Master PHP’s array_unique(): Remove Duplicates and Sort Arrays Efficiently

Learn how to use PHP’s array_unique() function to eliminate duplicate values from arrays, understand its parameters—including optional sort flags—and see practical code examples that demonstrate deduplication and sorting for both string and numeric arrays.

php Courses
php Courses
php Courses
Master PHP’s array_unique(): Remove Duplicates and Sort Arrays Efficiently

In PHP programming, the array_unique() function removes duplicate elements from an array and returns a new array.

The syntax is:

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

Parameter explanation:

$array

: the array to be deduplicated. $sort_flag: optional, determines how array elements are sorted.

Return value: the deduplicated array with only one instance of each duplicate.

Example of basic usage:

<?php
// Define an array with duplicate elements
$fruits = array("apple", "banana", "orange", "apple", "melon", "banana");

// Remove duplicates
$uniqueFruits = array_unique($fruits);

// Print the result
print_r($uniqueFruits);
?>

The output is:

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

When using array_unique(), an optional $sort_flag can be set to control sorting. Two possible values are:

SORT_STRING (default): treats elements as strings and sorts them lexicographically.

SORT_REGULAR: compares elements using regular comparison.

Example with SORT_STRING:

<?php
$numbers = array(1, 3, 5, 2, 5, 4);

// Remove duplicates and sort as strings
$uniqueNumbers = array_unique($numbers, SORT_STRING);

// Print the result
print_r($uniqueNumbers);
?>

The output is:

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

Summary

The array_unique() function efficiently removes duplicate elements from arrays in PHP. By specifying the optional $sort_flag, you can also control the sorting method during deduplication, simplifying array handling and improving code efficiency.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackenddeduplicationPHPSortingArraysarray_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

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.