faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input : Array Form Variables

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

27 of 31 people (87%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I loop through HTTP_POST_VARS to create a list of checked values from a form?

Oct 11th, 2002 00:37
Davi Koopman,


Imagine this is your form:

<form name="whatver" method="post" action="process.php">
<input type=checkbox name="var1" value="1" checked> var1<br>
<input type=checkbox name="var2" value="1" checked> var2<br>
<input type=checkbox name="var3" value="1"> var3<br>
<input type=checkbox name="var4" value="1" checked> var4<br>
<input type=checkbox name="var5" value="1"> var5<br>
.
.
.
<input type=checkbox name="var1000" value="1"> var1000<br>
<input type="submit" value="submit">
</form>

and you want to know which checkboxes are checked upon submition, you 
can loop through the HTTP_POST_VARS and produce a list of numbers like 
this:

<?php
while ( list($key, $value) = each ($HTTP_POST_VARS) ) {
   if ( ($value == 1) && ereg("var([0-9]+)", $key, $regs) ) {
       $listOfChecked[] = $regs[1];
    }
}

// at this point, $listOfChecked is an array
// whos values correspond to the boxes that
// were checked by the form.

// You can print them out like this:
for ($i=0; $i<count($listOfChecked); $i++) {
   print "Value: ".$listOfChecked[$i]."<br>\n";
   // do whatever other processing you want.
}
?>