sfarzoso
sfarzoso

Reputation: 1610

Cannot remove duplicate value from string

I want remove duplicate value from a string, so I'm using this code:

$new_order = '49850, 49850, 49851, 49852, 49853, 49854';
$new_order = implode(',', array_unique(explode(',', $new_order)));

output:

string(40) "49850, 49850, 49851, 49852, 49853, 49854"

but should be:

string(40) "49850, 49851, 49852, 49853, 49854"

Upvotes: 1

Views: 30

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57141

As you explode on just a comma, the second value is 49850 (with an extra space at the start).

So explode on a comma followed by a space

$new_order = '49850, 49850, 49851, 49852, 49853, 49854';
$new_order = implode(',', array_unique(explode(', ', $new_order)));

or, you can add array_map() in there to trim() each entry...

$new_order = implode(',', array_unique(array_map('trim', explode(',', $new_order))));

Upvotes: 2

Related Questions