For the record, I fully support Kris' method, and that is the way I would choose if this were for my project. However, I would just like to add that there are several additional ways to skin this cat:
Code: (Demo)
$raw = 'AAA,BBB,aAA,BbB,BbB,AAA';
// str_word_count() -> array_unique() -> implode()
echo implode(',',array_unique(str_word_count($raw,1)));
echo "\n";
// str_getcsv() -> array_unique() -> implode()
echo implode(',',array_unique(str_getcsv($raw)));
echo "\n";
// preg_match_all() -> array_unique() -> join()
echo join(',',array_unique(preg_match_all("/[A-Za-z]{3}/",$raw,$m)?$m[0]:array()));
echo "\n";
// preg_split() -> array_unique() -> join()
echo join(',',array_unique(preg_split("/,/",$raw)));
echo "\n";
// preg_replace() -> parse_str() -> implode()
parse_str(preg_replace('/(^|,)([A-Za-z]{3})/',"$2=$2&",$raw),$array);
echo implode(',',$array);
I have 5 different methods to explode the csv string without using explode()
.
1 method that doesn't use array_unique.
And of course implode()
and join()
can be used interchangeably as they are synonyms.
I think the fifth method is my favorite as it is the wackiest and doesn't use array_unique()
. *unfortunately it's a two-liner :{
p.s.
@Thiyagu says this is how the string is constructed:
forloop(){ $string .= $a[i].',';}
If that is true, then weeding out the duplicates can be done inside this loop by leveraging a temporary array. This has the added benefit of omitting the trailing comma that concatenation generates.
foreach($data as $value){
$result[$value]=$value; // duplicate values will be overwritten because arrays may not have two identical keys
}
echo implode(',',$result);
,
;array_unique()
, then implode with a,
– Inducement