1

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"

1
  • 2
    Your implode/explode dance doesn't account for the spaces. Commented Apr 24, 2020 at 10:48

1 Answer 1

2

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))));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.