Page 1 of 1

separate delimited text in field??

Posted: Thu Dec 20, 2007 7:11 pm
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.

Posted: Thu Dec 20, 2007 8:43 pm
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!

Posted: Fri Dec 21, 2007 8:42 am
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);