2

I have string of comma separated values.

1,2,3,4,4,4,4,4,4,4,4,01633,4,4

I need to remove the duplicates, so I though of using

array_unique($str);

However, it returns no results. So I decided to output it to see what I have:

print_r($str);
// returns: 1,2,3,4,4,4,4,4,4,4,4,01633,4,4

I'm a little lost. I checked if it is an array and I got true. Here's how that string is created:

$str = '1,2,3';

foreach ($a as $b) {
    $str.= ','.$b;
}

What am I missing here?

3 Answers 3

4
$str = explode(',', $str); // create array
$newArray = array_unique($str); // then process

actually, though... just do your array_unique() on $a before the string is created.

$a = array_unique($a);

then...

foreach ($a as $b) { // and so on
Sign up to request clarification or add additional context in comments.

3 Comments

Or in one line $newArray = array_unique(explode(',', $str)); ^_^
I actually need it as a comma separated values in the end, just no duplicates... Do i have to implode it back then?
If you go with the first way I suggested above, you could then create a string with implode(',', $newArray).
2

Convert to an array, remove the repeat values, convert to string

$str = 'whatever';
$arr = explode( ',', $str );
$newArr = array_unique( $arr );
$newStr = implode( ',', $newArr );

2 Comments

I actually tested to see if it was an array: is_array($str) ? 'Array' : 'not an Array'; and got Array...
@santa, then skip lines 1-2 and use lines 3-4. You shouldn't be storing an array value in a variable named $str.
1

Explode on comma, make unique, glue pieces back together:

$str = implode(',', array_unique(explode(',', $str)));

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.