<form action="exercise2.php" method="post">
Type your name: <input type="text" name="name2" ><br>
Toyota<input name="vehicle[]" type="checkbox" value="Toyota"><br>
Bmw<input name="vehicle[]" type="checkbox" value="Bmw"><br>
Audi<input name="vehicle[]" type="checkbox" value="Audi"><br>
Subaru<input name="vehicle[]" type="checkbox" value="Subaru"><br>
<input type="submit" name="submit">
</form>
**事情是这样;当我不选择任何车辆时,程序应该崩溃,以防万一。**
我想回声车辆,例如当选中两个或三个选项时。
<?php
$name = $_POST['name2'];
$vehicles = $_POST['vehicle'];
$cont=0;
foreach($vehicles as $i){
$cont++;
}
switch($cont){
case 0:
echo "You should choose some favs";
break;
case 1:
echo "$name, you should look for more fav cars";
break;
case 4:
echo "$name, I think you have too many fav cars";
break;
}?>
您正在尝试遍历不存在的数组。表单未选中时,不会在复选框上发送任何内容,因此您需要更改php:
<?php
# If you are echoing this back, it's good to sanitize it a bit
$name = htmlspecialchars($_POST['name2']);
# Make the default be an empty array
$vehicles = (!empty($_POST['vehicle']))? $_POST['vehicle'] : [];
$cont=0;
# This won't fail because it can iterate an empty array
foreach($vehicles as $i){
$cont++;
}
# 0 should now work
switch($cont){
case 0:
echo "You should choose some favs";
break;
case 1:
echo "$name, you should look for more fav cars";
break;
case 4:
echo "$name, I think you have too many fav cars";
break;
}
也打开错误,它会告诉您它无法遍历empty
。