separate delimited text in field??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
johnd123
Forum Newbie
Posts: 5
Joined: Thu Dec 20, 2007 6:47 pm

separate delimited text in field??

Post by johnd123 »

I sure hope someone can help me with this.

i think the solution is right in front of me but after trying for a few hours im at a dead end :cry:

Heres what i am trying to do..

I have a text field with a list of members which are comma separated, the amount of members can not be predetermined so has to be detected via php.

When the form is posted i need to then separate the members

i have tried, for example..

Code: Select all

// Post Members
$members = $_POST['members'];

//Calculate amount based on delimiter [,] - Works!
$amount = sizeof(explode(',',trim($members))); 

//Try and separate each member - This is where i have probs
for ($x=0;$x<$amount;$x++)
{
list($member) = explode(',',trim($members[$x]));

echo $member."<br>";

}
The above code prints out each letter on a new line instead of the members name

example: Should be

Member 1
Member 2
member 3
... and so on

I get

M
e
m
b
e
r

1
.... and so on

I hope you can understand this any help would be most greatful :D

Thanks in advance.
johnd123
Forum Newbie
Posts: 5
Joined: Thu Dec 20, 2007 6:47 pm

Post by johnd123 »

Ok ... i have solved the problem

here are 2 answers for anyone having the same problem

both work fine

Code 1 - Easiest Solution

Code: Select all

// Post Members
$members = $_POST['members'];

//Separate each member
$xmembers = explode(",",trim($members));
foreach ($xmembers as $val => $member)
{
echo $members."<br>";
}
Code 2 - 4 the for peeps

Code: Select all

// Post Members
$members = $_POST['members'];

//Separate each member
$xmembers = explode(",",trim($members));
for($x=0;$x< sizeof($xmembers);$x++)
{
list($member) = explode(",",trim($xmembers[$x]));

echo $member."<br>";

}
Hope this will save someone a few strands of hair lol

peace!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Your second snippet can be cleaned out further by removing the for loop entirely.

Code: Select all

// this will throw an error if the input is a multidimensional array
$members = array_map('trim', (is_array($_POST['members']) ? $_POST['members'] : explode(',', $_POST['members']));

echo implode('<br />', $members);
Post Reply