4

I created a image uploader which works by remote, so whenever a user enters a bunch of links, I want to prevent duplicate links being added so that the image isn't copied twice and is removed so it leaves the links to be unique without any duplicates.

$break = explode("\n", $links);
$count = count($break);

$unique_images = array();

for($i = 0; $i < $count; $i++)
{
    array_push($unique_images, $break[$i]); 
}

array_unique($unique_images);

The rest of the code works, but I'm just not getting why it isn't working, I also tried a foreach loop but that didn't help as well.

I have error_reporting set to E_ALL but there are no errors. I use var_dump on the array and I get this:

array(3) 
{ 
     [0]=> string(48) "http://localhost:8888/images/img/wallpaper-1.jpg" 
     [1]=> string(48) "http://localhost:8888/images/img/wallpaper-1.jpg" 
     [2]=> string(48) "http://localhost:8888/images/img/wallpaper-1.jpg" 
} 

How come the array_unique doesn't remove any duplicates?

MacMac
  • 34,294
  • 55
  • 151
  • 222

4 Answers4

4

array_unique returns the filtered array, instead of altering it. Change your last line into:

$unique_images = array_unique($unique_images)

and it should be working.

Pelle
  • 6,423
  • 4
  • 33
  • 50
3

array_unique() returns a new array, it does not modify the array in place:

Takes an input array and returns a new array without duplicate values.

$unique_images = array_unique($unique_images);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

You can just do:

$unique_images = array_unique(explode("\n", $links));

The array_unique function returns a new array with duplicates removed. So you need to collect its return value.

Also explode returns you an array which you can directly feed to array_unique.

codaddict
  • 445,704
  • 82
  • 492
  • 529
1
$unique_images = array_unique($unique_images);

otherwise you're simply discarding the result

Mark Baker
  • 209,507
  • 32
  • 346
  • 385