detecting duplicate string in a explode function php
how do i detect duplicate string i开发者_运维问答nside explode?
$str = 'a, b, c, a, a, a, b, e, w, r, d, o'; // example str
$explode = explode(',', $str);
any idea?
$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
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.
var_dump(array_unique(str_getcsv($str)));
精彩评论