如果选择多个,价格会上涨

时间:2018-07-17 01:55:11

标签: php html

我正在做一个项目。我的代码写在下面

HTML

<input type="checkbox" name="A" value="A">A
<input type="checkbox" name="B" value="B">B
<input type="checkbox" name="C" value="C">C
<input type="submit" name="submit" value="Submit">

PHP

<?php
$price=0;
  if(isset($_POST["submit"])){
  //the code goes here
  }
?>

如果仅选择一个选项,则它是免费的(无价格)。但是,如果用户选择多个选项,则每个选项中的$price为+10。因此,可以这样说明

  • 选择1 =免费
  • 选择2 = +10
  • 选择3 = +20

我不了解我的PHP,行//the code goes here仍然为空。有想法吗?

1 个答案:

答案 0 :(得分:0)

家庭作业,对吧?我什至不必上大学。

<?php

if( isset($_POST) )
{
  $count = 0;
  $arr = [
    array_key_exists('A', $_POST),
    array_key_exists('B', $_POST),
    array_key_exists('C', $_POST)
  ];

  for( $i = 0; $i < 3; $i++ ) {
    if( $arr[$i] ) $count++;
  }
  // Now count the total - 1 and * it by 10
  if( $count > 1 ) $total = ($count - 1) * 10;
}

基本上,此脚本将检查$_POST数组中的密钥,如果您未选择checkbox,则不会为_POST数组创建密钥,因此它将为false

如果为假,则默认情况下跳过。但是,如果它是true,它将增加到$count变量。然后,如果$count大于1,则添加一个新变量$total = $count - 1。这将从$count中删除一个值,然后乘以10。

相关问题