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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

1 Comment

@Youbook: that would be a replacement for your entire code snippet.
1
$unique_images = array_unique($unique_images);

otherwise you're simply discarding the result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.