Usman Adnan
Usman Adnan

Reputation: 19

take the duplicate values out of an array

i have a text field where users can enter a string of 15 numbers only per line 50 lines max

i also need to filter out any duplicate values. so far i have this code

if(empty($_POST['text_field'])){$message = 'Please input values for the text_field.';}else{
    $text_field = $_POST['text_field'] ;
    $lines_unfiltered = array_slice(explode("\n", $text_field), 0, 50);
    $lines = array_unique($lines_unfiltered);
    print_r($lines);
exit;

but when i run it it with these numbers

5645646546545
2564545454544
5645646546545

it gives me all three lines and doesnt filter out the duplicate like it should

Array([0]=> 5645646546545 [1]=> 2564545454544 [2]=> 5645646546545)

any ideas?

Upvotes: 1

Views: 109

Answers (1)

Jon Egeland
Jon Egeland

Reputation: 12613

So, as the comments have pointed out, you need to strip out the \ns on each string.

This could be done with:

trim($text_field);

Then you should be left with a properly formatted string that can be added to an array.

Or you could do the one-liner that the other Jon proposed:

$lines = array_unique(array_map('trim', array_slice(explode("\n", $text_field), 0, 50)));

I added the array_unique function around everything to ensure that the result is only unique values.

Upvotes: 1

Related Questions