Removing duplicate values within a comma separated list in PHP

做~自己de王妃 提交于 2019-12-01 13:50:30

When dealing with lists of things, it's easiest to use arrays. Comma-separated strings work alright for displaying things, but they're no fun to work with in code. With that in mind, I would recommend not even touching a comma until you finally display the data out to the screen.

Unfortunately, it sounds like you already have comma separated strings stored in your database. If this is something you can change, you may want to look into an alternative database structure using multiple tables with a one-to-many relationship between users and things they like. There's a lot that could be said about this, but it's not the subject of your question. The basic concept is called database normalization, as Havelock has already mentioned.

In the event the database structure cannot be changed and you must work the comma-separated lists, simply undo the comma separation and get them back into arrays in PHP. To do this, you'd use the explode() function:

$teststring = '1,2,3';
$test = explode(',', $asdfstring); // array(1, 2, 3)

Once you have arrays, PHP has some handy features for sorting, removing duplicates, etc. The one you're probably most interested in here is array_unique().

To put it back into a comma-separated list for display, simply use implode(), which does the opposite of explode() by taking an array and joining it with the separator of your choice (e.g., comma).

Now since you have multiple columns you're dealing with here, and you only want one list, you're going to have to build the array in multiple steps. If every one of these columns can contain multiple values, you can do the explosion thing on all of them:

$items_like = explode(',', $rows['items_like']);
$first_like = explode(',', $rows['first_like']);
$second_like = explode(',', $rows['second_like']);
$third_like = explode(',', $rows['third_like']);
$merged = array_merge($items_like, $first_like, $second_like, $third_like);

Or if first, second, and third will only contain one item, you could do this:

$items_like = explode(',', $rows['items_like']);
$other_likes = array($rows['first_like'], $rows['second_like'], $rows['third_like']);
$merged = array_merge($items_like, $other_likes);

Now remove duplicates:

$likes = array_unique($merged);

Now we're finally ready to add commas:

echo implode(', ', $likes);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!