Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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.

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.

$unique_images = array_unique($unique_images);

otherwise you're simply discarding the result

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top