回显基于所选项目的数量

问题描述 投票:1回答:1
<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;
}?>
javascript php html switch-statement case
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.