Wednesday, April 6, 2011

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?

From stackoverflow
  • 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.

    Omar Abid : what shall i say i don't understand much PHP my array is the same as something like that array[1] = string array[2] = string i want to delete the duplicates if found
  • 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.

    Omar Abid : normaly it should contain elements like the array above, but it's not currently acting like an array. Anyway I found a solution by creating a new array and filling it with the $linkphoto

0 comments:

Post a Comment