Backend Development 2 min read

PHP array_unique() – Removing Duplicate Values from an Array

This article explains how the PHP array_unique() function removes duplicate values from an array while preserving original keys, describes its optional sort_flags parameter, lists sorting constants, and provides a complete example with code and expected output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP array_unique() – Removing Duplicate Values from an Array

The article introduces the PHP array_unique() function, which takes an array and returns a new array with duplicate values removed while preserving original keys.

It explains that the function sorts values as strings, keeps the first occurrence of each value, and notes that key names remain unchanged. Optional sort_flags can modify sorting behavior using constants such as SORT_REGULAR , SORT_NUMERIC , SORT_STRING , and SORT_LOCALE_STRING .

Parameter details are provided: array – the input array, and sort_flags – optional flag to control sorting.

The function returns an array containing the unique values.

Example usage:

<?php
$input = array(
    "green" => "green",
    "red"   => "red",
    "b"     => "green",
    "red",
    "blue",
    "red"
);
$result = array_unique($input);
print_r($result);
?>

Output:

Array
(
    [green] => green
    [red]   => red
    [b]     => green
    [0]     => blue
)
backendarrayphp-functionsarray_uniqueduplicate
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.