Jump to content

Take spaces out of comma seperated list


micah1701

Recommended Posts

the user submits a list of keywords, each seperated by a comma.
I want to alphabitize the list and take the spaces out between the keywords.

here's what I'm doing:[code]<?php
$postedList = $_POST['keywords']; // "Cranberry, Banana, Apple"
$keywords = explode(",",$postedList); //create array

foreach($keywords as $keyword){
$keyword = trim($keyword); //remove spaces from each value in array
}
sort($keywords);  //sort the array alphabetically
$data = implode(",",$keywords); //turn the array back into a list

echo $data; //returns:  " Apple, Banana,Cranberry" (with spaces) ???
?>[/code]

it still has spaces? What am I missing?
Link to comment
Share on other sites

You didn't put the trimmed keywords back into the array

[code]foreach($keywords as $index=>$keyword){
$keyword = trim($keyword); //remove spaces from each value in array
$keywords[$index] = $keyword;
}[/code]

Edit: effigy has the better solution.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.