Is there a better (faster) solution to remove duplicates from a comma separated string?
public function d($dep) {
if (strpos($dep,',') !== false) {
$nd = explode(',',$dep);
$oa = array_unique($nd);
$nx = (count($oa) > 1) ? implode(",",$oa) : $oa[0];
}
else {
$nx = $dep;
}
return $nx;
}
Thanks guys.
You could use the uniqueness of array keys:
function d($dep) {
return implode(',', array_keys(array_flip(explode(',', $dep))));
}
array_flip
swaps the key-value association, so the values become the keys and vice versa. This will automatically eliminate duplicates. Its runtime complexity is O(n).
Try just this:
$uniqueDep = implode(',', array_unique(explode(',', $dep)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With