Omar Abid
Omar Abid

Reputation: 15976

The PHP function array_unique doesn't work

I have an array in PHP and I want to remove duplicates.

I simply turned to the function array_unique() to create a new array and remove the duplicates.

Here's the code:

$unlink = array();
$unlink = array_unique($linkphoto);

foreach ($unlink as $link) {
    echo $link, "<br />";
}

Still it shows duplicates! Any suggestions about what's wrong?

Upvotes: 0

Views: 2261

Answers (2)

Paolo Bergantino
Paolo Bergantino

Reputation: 488404

We need more context in order to be able to help you, like what the contents are of $linkphoto before array_unique is applied to it. For example:

<?php
$array = Array('A','B','C','D','B');
print_r($array); // Array ( [0] => A [1] => B [2] => C [3] => D [4] => B )
$result = array_unique($array);
print_r($result); // Array ( [0] => A [1] => B [2] => C [3] => D ) 
?>

As @nobody_ mentioned, it will only eliminate duplicates if their string representations are the same.

Upvotes: 1

Kyle Cronin
Kyle Cronin

Reputation: 79103

According to the documentation, the condition for equality is as follows:

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

What sort of data are you using? If two items aren't string equal, then they'll both remain in the array.

Upvotes: 2

Related Questions