if if condition使用条件运算符传递post值

时间:2014-10-16 08:43:10

标签: php if-statement conditional-statements conditional-operator

我想从Form Input发布条件运算符。在IF条件中使用已发布的运算符。无法执行任何逻辑来完成它。

<form action="" method="post" accept-charset="utf-8">
        <input name="postvalue"  size="5" maxlength="7" value=">=5">
            <p><input type="submit" value="Go"></p>
</form>

<?php 
if(10 $_POST["postvalue"]) {
    echo "Its greater than 5";
} else {
    echo "Its less than 5";
}


?>

1 个答案:

答案 0 :(得分:0)

你可能正在寻找这样的东西:

<form action="" method="post" accept-charset="utf-8">
        <input name="term"  size="5" maxlength="7" value=">=5">
            <p><input type="submit" value="Go"></p>
</form>

<?php 
// separate operator and operand from the posted value
preg_match('/^([=<>!]+)([0-9]+)$/', $_POST['term'], $tokens);
$operator = $tokens[1];
$operand  = $tokens[2];

// create an evaluation function
$check = create_function('$value', '
    $operand = '.$operand.';
    switch("'.$operator.'") {
    case "==": return ($value==$operand);
    case "!=": return ($value!=$operand);
    case "<":  return ($value<$operand);
    case "<=": return ($value==$operand);
    case ">":  return ($value>$operand);
    case ">=": return ($value>=$operand);
    default:   throw new Exception("invalid operator");
  }');

// apply the evaluation function to some value
try {
  if ($check(10)) {
      echo "10 is greater than 5";
  } else {
      echo "10 is less than 5";
  }
} catch (Exception $e) {
  echo sprintf('Exception: %s', $e->getMessage());
}
?>

显然必须添加错误检测等...

无论如何,这是一个非常奇怪的&#34;架构......考虑其他方法,因为这种方法有些容易出现故障。相反,您应该在单独的输入字段(后置字段)中发布操作数和运算符,以简化评估并使事情更加健壮。操作符可能应该作为选择输入提供,操作数作为数字微调器......