如何在php中正确使用switch函数

时间:2014-03-11 15:18:13

标签: php switch-statement

我想在单选按钮的值上使用开关功能,但我不知道如何正确使用它。

 if(isset($_POST['Itemtype']))
    {
    $Itemtype = $_POST["Itemtype"];                             
switch ($Itemtype)
    {
    case "Ingredient":
    $Brandname = $_POST["Brandname"];

if(isset($_POST['Brandname']))
    {
    $try2 = "Brandname working";
    }
    else
    {
    $errormsg = 'error on branchname';
    }
    break;
    case "Miscellaneous":
    $Size = $_POST["Size"];
    $Color = $_POST["Color"];
    if(isset($_POST['Size']))
    {
    $try2 = "Misc working";
    }
    else
    {
    $errormsg = 'error on size';
    break;
    }
  else
{
$errormsg = 'error5';
}

我对字符串部分的不好:)但它没有检查brandname是否设置为null。

2 个答案:

答案 0 :(得分:0)

问题是你的字符串不在引号ex:case杂项:应该是case" Miscellaneous":

答案 1 :(得分:0)

您忘记将Ingredient包装成“所以您的代码应如下所示:

if(isset($_POST['Itemtype'])){

  $Itemtype = $_POST["Itemtype"];  
  switch ($Itemtype){

    case "Ingredient":
       $Brandname = $_POST["Brandname"];

       if(isset($_POST['Brandname'])){
        $try2 = "Brandname working";
       }
       else{
        $errormsg = 'error on branchname';
       }
    break;


    case "Miscellaneous":
      $Size = $_POST["Size"];
      $Color = $_POST["Color"];

      if(isset($_POST['Size'])){
        $try2 = "Misc working";
      }
      else{
        $errormsg = 'error on size';
      }
    break;

  }

}
else{
  $errormsg = 'error5';
}