3

how do i detect duplicate string inside explode?

$str = 'a, b, c, a, a, a, b, e, w, r, d, o'; // example str
$explode = explode(',', $str);

any idea?

SOer
  • 139
  • 1
  • 7
  • 13

3 Answers3

6
$explode = explode(',',$str);
$unique = array_unique($explode);
if(sizeof($explode) != sizeof($unique)){
    echo "There are duplicates";
}else{
    echo "No duplicates";
}

I suggest using explode(', ',$str); so you can avoid all those extra spaces

stormdrain
  • 7,915
  • 4
  • 37
  • 76
GWW
  • 43,129
  • 11
  • 115
  • 108
5

You can use array_unique()

but be wary of the spaces: they will be part of each array element if you use explode(). If you enter an extra space somewhere, array_unique won't detect the duplicate any more.

Use the second example in the manual page on trim() to shave off the spaces before doing the array_unique() for a more reliable comparison.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0
var_dump(array_unique(str_getcsv($str)));
bcosca
  • 17,371
  • 5
  • 40
  • 51