Reputation: 788
i have a php string
$select_columms = 'pid, p.title, caption, filepath, filename, encaption, user1, user2, user3, user4, user5, user6, ult_puja, p.title, user2, user3';
so i had this idea i could get a unique string with this line of code
$select_columns = implode(',', array_unique(array_filter(explode(',',$select_columns))));
but it doesn't seem to work can you see what i am missing?
edit: thanks for the help my final code is:
$select_columns = implode(',', array_filter(array_unique(explode(',', $select_columns))));
which outputs $select_columns = 'pid, p.title, caption, filepath, filename, encaption, user1, user2, user3, user4, user5, user6, ult_puja'
i use the array_filter in case i have input like ', pid,'
Upvotes: 0
Views: 3729
Reputation: 50009
Try this out
echo implode(',', array_unique(explode(',', $select_columms)));
EDIT As @amitchd pointed out. Fails hard when not trimmed. Fixed now
And if your string has uneven spacing, you can do this
$select_columms = 'pid, p.title, caption, filepath, filename, encaption, user1, user2, user3, user4, user5, user6, ult_puja, p.title, user2, user3';
$arr = explode(',', $select_columms);
array_walk($arr, '_trim');
echo implode(',', array_unique($arr));
function _trim(&$value) {
$value = trim($value);
}
Upvotes: 3
Reputation: 503
Columns was spelt wrong, array_filter was unnecssary and the explode/implode were missing a space after the comma.
<?php
$select_columns = 'pid, p.title, caption, filepath, filename, encaption, user1, user2, user3, user4, user5, user6, ult_puja, p.title, user2, user3';
$select_columns = implode(', ',array_unique(explode(', ',$select_columns)));
var_dump($select_columns);
?>
Upvotes: 0
Reputation: 195
JohnP's answer should work. As a personal preference, I'd separate this out to two lines at least. Three functions on a single line can be hard to read...
Upvotes: 0
Reputation: 16280
seems fine to me. 2 issues:
1) you've spelt "columns
" wrong in the variable declaration
2) array_filter()
is redundant here - it works exactly the same without it.
demo:
$ php -a
Interactive shell
php > $select_columns = 'pid, p.title, caption, filepath, filename, encaption, user1, user2, user3, user4, user5, user6, ult_puja, p.title, user2, user3';
php > echo implode(',', array_unique(explode(',',$select_columns)));
pid, p.title, caption, filepath, filename, encaption, user1, user2, user3, user4, user5, user6, ult_puja
php >
Upvotes: 1