Page 1 of 1
Making loads of variables with a loop
Posted: Wed Aug 08, 2007 4:00 pm
by rabw
Hi everyone, this is probably a really simple thing but I'm still new to php and now stuck on it.
This is what I have...
Code: Select all
for ( $counter = 1; $counter <= 5; $counter += 1)
{
if (!empty($_POST["rcpt".$counter])){$rcpt[$counter] = $_POST["rcpt".$counter];}
}
What I want to do is create automatically in a loop a load of variables
if the post data exists - it's likely to be for 1-500 or more, but just trying 1-5 while I see if it'll work...
Code: Select all
$rcpt1 = $_POST["rcpt1"];
$rcpt2 = $_POST["rcpt2"];
$rcpt3 = $_POST["rcpt3"];
$rcpt4 = $_POST["rcpt4"];
$rcpt5 = $_POST["rcpt5"];
any ideas?
Thanks
Richard.
Posted: Wed Aug 08, 2007 4:03 pm
by s.dot
Your rcpts, i'd imagine, are coming from a form.
Name the form like this.
Code: Select all
<?php echo '<input type="text" name="rcpt[]" size="20" />'; ?>
This way, you'll have an array of rcpt's in $_POST['rcpt'].
To filter out blank receipts, use array_filter().
Code: Select all
$rcpts = array_filter($_POST['rcpt']); echo '<pre>'; print_r($_POST['rcpt']); echo '</pre>';
Posted: Wed Aug 08, 2007 4:15 pm
by rabw
Hi, thanks or the reply!
I think the array_filter could work for me, but unfortunately it is coming from a form but not php - it's an xml/xsl form which also does its own loop to add the number to the end of rcpt... Maybe the php needs to go and take stuff from the xml rather than using xsl to submit the data to the php? Other than this I've posted about (to prevent having to write 500 lines, and possibly making the php slow in the process?) everything else is working ok for me.
EDIT: "unfortunately it is coming from a form but not php" Just realised I may have been being dumb here?
Posted: Wed Aug 08, 2007 5:02 pm
by s.dot
Someone once told me that if it ends in numbers, it should be in an array. Even if it is coming from XML, SimpleXML could easily parse each node into an array.
But anyways, if you want to go your route, you'll need to use variable variables.
Code: Select all
for(loop)
{
${'rcpt' . $counter} = $_POST['rcpt' . $counter];
}
Posted: Wed Aug 08, 2007 6:15 pm
by Ollie Saunders
name="rcpt[]"
Won't work on all browsers. Specify indexes like this: name="rcpt[0]"