Log in

View Full Version : foreach array only returns one result



JShor
01-29-2008, 04:38 PM
Aloha!

I have foreach() to parse each checkbox value a user selects separately. It worked fine before I used it in an IF expression-but now it's not. Without the IF, if the user doesn't select any checkbox and DOES submit the form, the foreach won't recognize any data (obviously) and will return w/an error. Below is the code of the page:



<?php

$a = $_GET['a'];

if($a == 'a') {

$state = $_POST['state'];


if(!$state) {



echo "<font color=red>Please select a state</font>";

} else {
foreach ($state as $statename);
{
echo "$statename is checked";
}

}


}

?>
<form action="test.php?a=a" method="post">
<input type="checkbox" value="New York" name="state[]">New York<br />
<input type="checkbox" value="Maryland" name="state[]">Maryland<br />
<input type="submit">
</form>


Thanks!

djr33
01-29-2008, 10:37 PM
$state = $_POST['state']; //set state to something even if null (probably with a warning
if(!$state) { //now, regardless of the form, it has the value of $_POST['state'], or null
//this is always true