Removing duplicates with array_unique

I created an image downloader that works remotely, so whenever a user enters a link bundle, I want duplicate links not to be added, so that the image is not duplicated and deleted, so it leaves the links 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 just don’t understand why it does not work, I also tried the foreach , but that didn't help either.

I have error_reporting set to E_ALL , but no errors. I use var_dump in an array and I get the following:

 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" } 

Why doesn't array_unique remove duplicates?

+4
source share
4 answers

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

It takes an input array and returns a new array with no duplicate values.

 $unique_images = array_unique($unique_images); 
+3
source

array_unique returns a filtered array instead of changing it. Change your last line to:

 $unique_images = array_unique($unique_images) 

and it should work.

+4
source

You can simply do:

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

The array_unique function returns a new array with duplicates removed. Therefore, you need to collect the return value.

Also explode returns you an array that you can directly pass to array_unique .

+2
source
 $unique_images = array_unique($unique_images); 

otherwise you just discard the result

+1
source

All Articles