PHP

Remove Duplicate Values from an Array While Preserving Keys

Learn to remove duplicate values from a PHP array, keeping only unique elements, and importantly, preserving the original array keys using `array_unique` in PHP.

<?php

$data = [
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'apple',
    'd' => 'orange',
    'e' => 'banana',
    'f' => 'grape'
];

$uniqueData = array_unique($data);
print_r($uniqueData);

$numericArray = [0 => 1, 1 => 2, 2 => 1, 3 => 3, 4 => 2];
$uniqueNumericArray = array_unique($numericArray);
print_r($uniqueNumericArray);

$mixedTypes = [1, "1", 2, "2", "apple", "Apple"];
// SORT_REGULAR compares items normally (default).
$uniqueMixedTypes = array_unique($mixedTypes, SORT_REGULAR);
print_r($uniqueMixedTypes);

// SORT_STRING treats all items as strings for comparison.
$uniqueMixedTypesString = array_unique($mixedTypes, SORT_STRING);
print_r($uniqueMixedTypesString);

/*
Output:
Array
(
    [a] => apple
    [b] => banana
    [d] => orange
    [f] => grape
)
Array
(
    [0] => 1
    [1] => 2
    [3] => 3
)
Array
(
    [0] => 1
    [1] => 2
    [4] => apple
    [5] => Apple
)
Array
(
    [0] => 1
    [2] => 2
    [4] => apple
)
*/
How it works: The `array_unique()` function filters an array, returning a new array with unique values. Crucially, it preserves the original array keys for the first occurrence of each unique value. You can pass a second argument, `sort_flags`, to control how values are compared. `SORT_REGULAR` (default) compares items normally, `SORT_STRING` treats all items as strings, and `SORT_NUMERIC` treats them as numbers, which is important for distinguishing between 1 and '1' or similar.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs