开发者

PHP actions if checkboxes are selected!

I have a form with 3 checkboxes, and my idea is run some commands if they are selected and do something else if they are not selected.

for($i=1; $i<=3; $i++)
{
    if ($_POST['option'.$i])
    {
    echo "123";
    }
    if (!$_POST['option'.$i]) 
    {
    echo 开发者_开发百科"456";
    }
}

But if they are not selected the commands are not executed.. The if statement is correct?


No, what you should be doing is checking them like this:

if (isset($_POST['option'.$i]))

Otherwise, you are just trying to evaluate the boolean form of whatever is in that $_POST element. Why is this bad? Suppose the value of that field were 0. Even though the checkbox was checked, your code wouldn't run.

Documentation for isset()


Sure, that will work just fine.

If you want to slightly de-uglify your code, you can do it this way:

<input type="checkbox" name="options[option_name]" value="1" />
<input type="checkbox" name="options[second_option_name]" value="1" />

if(isset($_POST['options']) && is_array($_POST['options']) {
  foreach($_POST['options'] as $option_name => $ignore_this) {
    switch($option_name) {
      case 'option_name':
        // do something
        break;
      case 'second_option_name':
        // do something else
        break;
  }
}

}


You can use an if ... else:

  if ($_POST['option'.$i])
   {
      echo "123";
   }
   else 
   {
     echo "456";
   }

to avoid checking the same condition twice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜