Using the select
SOURCE CODE:
<html>
<head><title>Form Collection with a select</title></head>
<body>
<h1>Using the select</h1>
<form method="post" name="frmD" action="282ln08DropDownList.php">
<select size="5" name="fruits[]" multiple>
<option value="apple"> Apples</option>
<option value="pear"> Pears</option>
<option value="peach"> Peaches</option>
<option value="watermelon"> Watermelon </option>
<option value="grape"> Grapes </option>
</select> <br>
<br>Do you like fruit?<br>
<input type="checkbox" name="chkName1" value=yes checked>Yes
<input type= "checkbox" name="chkName1" value=no>No
<br><br>
<input type="submit" value="Submit" name="btnSubmit"> Why do we get an error?
Let's look at the code...</form>
<?
// With PHP, we'll get an error if nothing is posted to form without this code in BLUE
if ((isset($_POST['fruits'])) && (isset($_POST['chkName1']))) {
$fruits=$_POST['fruits'];
$chkName1=$_POST['chkName1'];
} else {
$fruits="";
$chkName1="";
}
?>
<? if (($fruits != "") && ($chkName1 != "")) { ?>
<b>Your choice of fruits:</b><br>
<? echo $fruits[0] ?> <br>
<? echo $fruits[1] ?> <br> NOTE: This is line 33
<b>Your answer to do you like fruit?</b><br>
<? echo $chkName1 ?>
<? } else { ?>
<? } ?><br><br>
<br>
</body></html>
ERROR: We get an "Warning: Undefined offset: 1 in C:\Documents and Settings\Administrator\Desktop\Web\282\282ln08DropDownList.php on line 33
" if we do not select at least two fruits.
Note that this code attempts to write two elements (0 & 1) of the FRUITS selection list. If we only
pick one, it attempts to write the second element of the array, which does not exist. We can fix it
with a FOR...NEXT loop. Also, note that if we pick more than two, only the first two elements are displayed.
Let's fix it with a FOR...NEXT loop HERE.