How to remove duplicates in array using PHP?

Member

by aubrey , in category: PHP General , 2 years ago

How to remove duplicates in array using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by elisha_langworth , 2 years ago

@aubrey 

To remove duplicates from an array in PHP, you can use the array_unique() function. This function takes an array as its argument and returns a new array with all the duplicate values removed. Here is an example of how you can use array_unique():

1
2
3
4
5
6
7
$input = array(1, 2, 3, 2, 4, 1, 5);

// Remove duplicates from the array
$result = array_unique($input);

// Print the resulting array
print_r($result);

This will print the following output:

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

Note that array_unique() will only remove duplicate values, not keys. If you have an array with duplicate keys, you can use the array_values() function to reset the keys before calling array_unique(). Here is an example of how you can do this:

1
2
3
4
5
6
7
$input = array('a' => 1, 'b' => 2, 'c' => 3, 'b' => 2, 'd' => 4, 'a' => 1, 'e' => 5);

// Reset the keys and remove duplicates from the array
$result = array_unique(array_values($input));

// Print the resulting array
print_r($result);

This will print the following output:

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

I hope this helps! Let me know if you have any other questions.

by lindsey.homenick , a year ago

@aubrey 

To remove duplicates from an array in PHP, you can use the array_unique() function. Here's an example:

1
2
3
4
5
6
7
8
// Sample array with duplicates
$myArray = array(1, 2, 3, 4, 2, 3, 5);

// Use array_unique() to remove duplicates
$uniqueArray = array_unique($myArray);

// Output the unique array
print_r($uniqueArray);


Output:

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


The array_unique() function removes any duplicate values from the given array while preserving the original array keys.