Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates with array_unique

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?

like image 239
MacMac Avatar asked Dec 29 '22 06:12

MacMac


2 Answers

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.

like image 93
Pelle Avatar answered Jan 12 '23 00:01

Pelle


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);
like image 27
Felix Kling Avatar answered Jan 11 '23 23:01

Felix Kling