PASSWORD RESET

Your destination for complete Tech news

PHP

How to remove duplicate values from an array in PHP?

485 0
< 1 min read

To remove duplicate values from an array in PHP, you can use the array_unique function. This function removes duplicate values from an array and returns a new array with only unique values.

Here’s an example:

$array = [1, 2, 3, 1, 2, 3, 4, 5];
$unique = array_unique($array);

// $unique is now [1, 2, 3, 4, 5]

You can also use the array_values function to re-index the array after removing the duplicates:

$array = [1, 2, 3, 1, 2, 3, 4, 5];
$unique = array_values(array_unique($array));

// $unique is now [1, 2, 3, 4, 5] with sequential keys starting from 0

If you want to preserve the keys of the original array, you can use the array_keys function to get an array of the keys, and then use the array_combine function to create a new array with the unique keys and values:

$array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 1,
    'e' => 2,
    'f' => 3,
    'g' => 4,
    'h' => 5,
];

$keys = array_keys($array);
$values = array_unique($array);
$unique = array_combine($keys, $values);

// $unique is now ['a' => 1, 'b' => 2, 'c' => 3, 'g' => 4, 'h' => 5]

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.