为了账号安全,请及时绑定邮箱和手机立即绑定

基于所选项目数量的回声

基于所选项目数量的回声

MMMHUHU 2021-12-23 19:53:43
<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>** 事情是这样的;当我不选择任何车辆时,程序崩溃,当它应该在情况 1 中时。**我想回应车辆,例如检查两种或三个选项时。<?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;}?>
查看完整描述

1 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

您正在尝试遍历不存在的数组。未选中时,表单不会在复选框上发送任何内容,因此您需要更改 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。


查看完整回答
反对 回复 2021-12-23
  • 1 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号